其实就是模仿强类型语言比如Java、C/C++声明变量类型加快编译的速度
class MyTest:
name: str
age: int
def __init__(self, name: str = 'jjw', age: int = 18):
self.name = name
self.age = age
def test(self):
print('name: ' + self.name + "\nage: " + str(self.age))
my_test = MyTest()
# 有默认值则使用默认值
my_test.test()
print('*'*50)
my_test = MyTest("张三", 19)
my_test.test()
print('*'*50)
my_test = MyTest(20, '李四')
my_test.test()
输出结果:
name: jjw
age: 18
**************************************************
name: 张三
age: 19
**************************************************
Traceback (most recent call last):
File "/Users/jjw/Desktop/后端项目/yolov5_v3/my_test.py", line 20, in <module>
my_test.test()
File "/Users/jjw/Desktop/后端项目/yolov5_v3/my_test.py", line 10, in test
print('name: ' + self.name + "\nage: " + str(self.age))
TypeError: can only concatenate str (not "int") to str
从输出结果来看如果指定了类型,并且传错了变量的类型,则会直接报错
|