【发布时间】:2019-09-21 04:26:02
【问题描述】:
我是 python 的新手,我对类中属性的类型有一些疑问。根据 C 语言的经验,我觉得你应该总是在创建变量时定义它的类型,但在 Python 中似乎不是。
我正在尝试创建一个具有 3 个属性的类。在 Pycharm 中使用 Python 3.7。
一种方法是这样做
class Solution:
next: int
f_star: tuple
t_star: list
另一种方式是这样的
class Solution:
def __init__(self,):
self.next = int
self.f_star = tuple
self.t_star = list
但它们都没有真正将属性限制为相应的类型。我仍然可以执行说
node = Solution
node.t_star = 5
然后我运行它以在分配新值之前测试属性的类型。所以我这样做了:
node = Solution
print(type(node.next))
在第一种情况下,它正确返回类型
AttributeError: type object 'Solution' has no attribute 'f_star'.
谁能解释一下为什么会有这样的区别以及定义类的两种方式有什么区别。
以及如何或者是否需要在python中定义一个类的属性类型?
【问题讨论】:
标签: python-3.x class types attributes