它是类属性、实例属性和动态属性。当您这样做时:class Car():
def __init__(self):
pass
c = Car()
c.speed = 3
c.time = 5
speed和time是动态属性(不确定这是否是正式术语)。如果类的用法是在调用Car的任何其他方法之前设置这些属性,那么这些方法可以使用self.speed。否则,将出现一个错误:
^{pr2}$
发生这种情况是因为对于c,速度和时间是Car实例的属性。它们的存在或价值不会在其他Car实例中传播。因此,当我创建d并尝试查找d.speed时,该属性不存在。正如你在自己的评论中所说的,“当它们第一次被分配到时,它们就会出现。”I accidentally found that I don't have to init attributes in init. I learn from every tutor I have to put assignment in init like below.
你的导师错得很厉害,或者你误解了他们的意思。在您给出的示例中,每辆车的首字母speed和{}。通常,__init__将如下所示:class Car():
def __init__(self, speed, time): # notice that speed and time are
# passed as arguments to init
self.speed = speed
self.time = time
然后您可以用Car初始化Car。或者在init中输入默认值(如果是可选的)。在class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
>>> d.age = 3 # dynamic attribute/variable, unique to d
>>> d.age
3
>>> e.age # e doesn't have it at all
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Dog' object has no attribute 'age'