Python 是动态语言,变量随时可以被赋值,且能赋值为不同的类型
Python 不是静态编译语言,变量类型实在运行期决定的
动态语言很灵活,但是这种特性也是弊端
请看以下例子:
def add(x, y):return x + yprint(add(3, 5))
print(add('hello', 'world'))
print(add('hello', 5))
8
helloworld
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-238-6e69a92ee60e> in <module>4 print(add(3, 5))5 print(add('hello', 'world'))
----> 6 print(add('hello', 5))<ipython-input-238-6e69a92ee60e> in add(x, y)1 def add(x, y):
----> 2 return x + y3 4 print(add(3, 5))5 print(add('hello', 'world'))TypeError: can only concatenate str (not "int") to str
如何解决这种动态语言定义的弊端呢?有以下两种方法。
这只是一个惯例,不是强制标准,不能要求程序员一定要为函数提供说明文档
函数定义更新了,文档未必同步更新
def add(x, y):""":param x:int:param y: int:return: int"""return x + yprint(help(add))
Help on function add in module __main__:add(x, y):param x:int:param y: int:return: intNone
__annotations__
属性中i:int = 5
def add(x:int, y:int) -> int:""":param x:int:param y: int:return: int"""return x + yprint(help(add))
print(add.__annotations__)
Help on function add in module __main__:add(x: int, y: int) -> int:param x:int:param y: int:return: intNone
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}Process finished with exit code 0
如果对函数参数类型进行检查,有如下思路:
__annotations__
属性是一个字典,其中包括返回值类型的声明。inspect
模块本文发布于:2024-01-30 04:49:28,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170656137219335.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |