python函数定义中需要注意的几个点
函数定义
定义函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个tuple。
python空参数
What does ->
mean in Python function definitions?
In Python, the "->" symbol is used to indicate the return type of a function. It is part of the function definition in a Python 3.5 or later. For example, the following code defines a function add that takes in two arguments, a and b, and returns the sum of the two arguments.
def add(a: int, b: int) -> int:
return a + b
The ->
int at the end of the function definition indicates that the function returns an integer. This is known as type hinting and is used to help with code readability and debugging.
Please note that this feature is not enforced in Python and it's just used as a hint for developer and IDEs.
It's a function annotation.
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.
There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.
Python中变量名后面加冒号, 函数后面加箭头
def f(text:str,max_len:'int>0'=80) ->str:
return True
函数声明中,text:str
text 是参数 : 冒号后面 str是参数的注释。
如果参数有默认值,还要给注释max_len:'int>0'=80
->str
是函数返回值的注释。
这些注释信息都是函数的元信息,保存在f.__annotations__
字典中
需要注意,python对注释信息和f.__annotations__的一致性,不做检查
不做检查,不做强制,不做验证!什么都不做。
一个例子:
def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
print("函数注释", f.__annotations__)
print("参数值打印", ham, eggs)
print(type(ham),type(eggs))
f("www")
# >>> 函数注释 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing to see here'}
# >>> 参数值打印 www spam
# >>> <class 'str'> <class 'str'>
解释说明:
注释的一般规则是参数名后跟一个冒号(:),然后再跟一个expression,这个expression可以是任何形式。
返回值的形式是 -> int,annotation可被保存为函数的attributes。
以上属于静态注释,还有一种方法叫做动态注释
动态注释的原理,就是在函数中或者装饰器中动态的增加 删除 更改 注释内容
f.__annotations__是一个字典,可以使用字典的所有操作,这样就可以动态的更改注释了
python函数参数传递
可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。
关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。
在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。
但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
参考廖雪峰-函数的参数
[编程基础] Python中*args和**kwargs参数的使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具