Appearance
函数
Go
TODO
Python
- 函数定义
python
def greet(name):
print(f"你好, {name}!")
greet("张三")
# 输出: 你好, 张三!- 位置参数
python
def add(a, b):
return a + b
print(add(2, 3)) # 5- 默认参数
python
def greet(name="宝"):
print(f"你好, {name}!")
greet() # 你好, 宝!
greet("张三") # 你好, 张三!- 可变参数
python
def demo(*args, **kwargs):
print("位置参数:", args)
print("关键字参数:", kwargs)
demo(1,2,3,a=4,b=5)
# 输出:
# 位置参数: (1, 2, 3)
# 关键字参数: {'a': 4, 'b': 5}return可以返回值,没有 return 默认返回None
python
def square(x):
return x**2
res = square(5)
print(res) # 25- 匿名函数(Lambda)
python
square = lambda x: x**2
print(square(5)) # 25- 高阶函数(函数作为参数 / 返回函数)
python
def apply(func, value):
return func(value)
print(apply(lambda x: x*2, 10)) # 20Python 函数本质就是 对象 → 可以传递、赋值、返回
嵌套函数
python
def outer(x):
def inner(y):
return x + y
return inner
f = outer(5)
print(f(3)) # 8- 装饰器(Decorator,函数包装器)
python
def deco(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@deco
def say_hello():
print("Hello")
say_hello()
# 输出:
# Before
# Hello
# AfterJava
TODO