![](/img/trans.png)
[英]python - Accessing superclass's class attribute in super().__init__()
[英]python class's attribute not in __init__
我想知道以下代码为何起作用?
#!/usr/bin/env python3
import sys
class Car():
def __init__(self):
pass
if __name__ == '__main__':
c = Car()
c.speed = 3
c.time = 5
print(c.speed, c.time)
我偶然发现,我不必在init中设置init属性。 我从每位导师那里学习,我必须像下面这样将作业放在init中。
#!/usr/bin/env python3
import sys
class Car():
def __init__(self):
self.speed = 3
self.time = 5
if __name__ == '__main__':
c = Car()
print(c.speed, c.time)
如果有一些官方文件可以解释,那会更好。
它是类属性vs实例属性vs动态属性。 当您这样做时:
class Car():
def __init__(self):
pass
c = Car()
c.speed = 3
c.time = 5
speed
和time
是动态属性(不确定这是否是正式术语) 。 如果该类的用法是在调用Car
任何其他方法之前设置了这些属性,则这些方法可以使用self.speed
。 否则,您将得到一个错误:
>>> d = Car()
>>> d.speed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Car' object has no attribute 'speed'
>>>
发生这种情况是因为对于c
,速度和时间是Car
实例上的属性。 它们的存在或价值不会在Car的其他实例中传播。 因此,当我创建d
然后尝试查找d.speed
,该属性不存在。 正如您在自己的评论中所说, “它们在首次分配给它们时就已经存在。”
我无意间发现我不必在init中使用init属性。 我从每位导师那里学习,我必须像下面这样将作业放在init中。
您的导师很错,或者您误解了他们的意思。 在您给出的示例中,每辆汽车都具有相同的初始speed
和time
。 通常, __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
: c = Car(3, 5)
。 或者将默认值放入init(如果可选)。
编辑:改编自docs的示例:
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 "<stdin>", line 1, in <module>
AttributeError: 'Dog' object has no attribute 'age'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.