Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用字段上的类型提示定义Python类 在C++中,当我定义一个类时,用户立即知道每个字段的类型: class Person { string name; int age; }_Python_Python 3.x_Type Hinting - Fatal编程技术网

如何使用字段上的类型提示定义Python类 在C++中,当我定义一个类时,用户立即知道每个字段的类型: class Person { string name; int age; }

如何使用字段上的类型提示定义Python类 在C++中,当我定义一个类时,用户立即知道每个字段的类型: class Person { string name; int age; },python,python-3.x,type-hinting,Python,Python 3.x,Type Hinting,我想在Python中也这样做,即定义如下的类: class Person: name: str age: int 但这是行不通的。 在Python中有这样做的方法吗?在调用Python之前,您需要定义初始化类 self=>表示对象名称 class Person: def __init__(self): self.name = str() self.age = int() 我自己找到了答案——错误发生在python 3.5中。我编写的代码在Pyt

我想在Python中也这样做,即定义如下的类:

class Person:
     name: str
     age: int
但这是行不通的。
在Python中有这样做的方法吗?

在调用Python之前,您需要定义初始化类

self=>表示对象名称

class Person:
    def __init__(self):
     self.name = str()
     self.age = int()

我自己找到了答案——错误发生在python 3.5中。我编写的代码在Python3.7中运行良好

#!python3.7

class Person:
    name:str
    age:int

p = Person()
print(p)

我把它放在这里,以防其他人也有同样的问题。

即使你已经回答了你的问题,我也会把这个留给未来的读者

与Java、C或其他类似语言不同,Python变量是标识符。它们只是“名称”,用于标识存储在特定
名称下的“数据”。话虽如此,让我用一个例子来证明这一点(相对于你的问题)

在Person类中,我将
name
设置为字符串,将
age
设置为整数。这仅仅是为了代码的可读性,这样,如果有人使用我的类,他们就会知道该类需要什么

运行此模块时的输出:

python3 test.py
Hello Dave, I see you are 12 years old!
Hello 12, I see you are Dave years old!
从输出中可以看到,提供的数据类型不包含任何逻辑,只是为了提高代码可读性

python3 test.py
Hello Dave, I see you are 12 years old!
Hello 12, I see you are Dave years old!