【问题标题】:How to define a Python class with type-hints on the fields如何在字段上定义带有类型提示的 Python 类
【发布时间】:2020-04-24 19:02:53
【问题描述】:
在 C++ 中,当我定义一个类时,用户立即知道每个字段的类型:
class Person {
string name;
int age;
}
我想在 Python 中做同样的事情,即定义一个这样的类:
class Person:
name: str
age: int
但这不起作用。
有没有办法在 Python 中做到这一点?
【问题讨论】:
标签:
python
python-3.x
type-hinting
【解决方案1】:
我自己找到了答案——错误发生在 python 3.5 中。我编写的代码在 python 3.7 中完美运行。
#!python3.7
class Person:
name:str
age:int
p = Person()
print(p)
我把它放在这里以防其他人有同样的问题。
【解决方案2】:
即使你已经回答了你的问题,我还是要把这个留给未来的读者。
与 Java、C 或其他此类语言不同,Python 变量是标识符。它们只是用于识别存储在特定name 下的“数据”的“名称”。话虽如此,让我用一个例子来证明这一点(相对于你的问题)
class Person():
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def _printer(self):
print(f'Hello {self.name}, I see you are {self.age} years old!')
dave_1 = Person("Dave", 12)
dave_2 = Person(12, "Dave")
dave_1._printer()
dave_2._printer()
在 Person 类中,我将 name 设置为字符串,将 age 设置为整数。这只是为了代码的可读性,因此如果有人要使用我的课程,他们就会知道课程的期望。
该模块运行时的输出:
python3 test.py
Hello Dave, I see you are 12 years old!
Hello 12, I see you are Dave years old!
从输出可以看出,提供的数据类型没有逻辑,只是为了提高代码的可读性!
【解决方案3】:
你需要在调用pythons之前定义初始化类。
self => 代表你的对象名称。
class Person:
def __init__(self):
self.name = str()
self.age = int()