函数与异常
函数:比 Java 灵活很多
Section titled “函数:比 Java 灵活很多”def add(a, b): return a + b默认参数(Java 要靠重载才能实现)
Section titled “默认参数(Java 要靠重载才能实现)”def greet(name, greeting="Hi"): return f"{greeting}, {name}"
greet("Tom") # Hi, Tomgreet("Tom", "Hello") # Hello, Tom关键字参数:调用时能乱序
Section titled “关键字参数:调用时能乱序”def connect(host, port, timeout): ...connect(port=8080, host="localhost", timeout=30) # 顺序随便,可读性高函数是「一等公民」
Section titled “函数是「一等公民」”可以当参数传、赋值给变量、塞进列表:
def apply(fn, x): return fn(x)
double = lambda n: n * 2 # lambda 跟 Java 的差不多apply(double, 5) # 10异常处理:try / except
Section titled “异常处理:try / except”关键字和 Java 不一样:except 不是 catch,finally 一样。
try: result = 10 / 0except ZeroDivisionError as e: print(f"除零了: {e}")except (ValueError, TypeError): # 一次抓多种 print("值或类型错误")else: print("没出错才执行") # Java 没有这个finally: print("一定执行")def set_age(age): if age < 0: raise ValueError("年龄不能为负") # 用 raise,不是 throw| Java | Python |
|---|---|
try | try |
catch | except |
finally | finally |
throw | raise |
throws(方法签名) | 无,Python 不强制声明 |
- [[02-数据结构]] —— 返回多值用 tuple
- [[04-面向对象]] —— 方法本质也是函数
- [[01-基础语法与变量类型]]