python class 的属性不在 __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 中,如下所示。

#!/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)

如果有官方文档可以解释一下就更好了。

它是 class 属性与实例属性与动态属性。当你这样做时:

class Car():
    def __init__(self):    
        pass

c = Car()
c.speed = 3
c.time = 5

speedtime是动态属性(不确定这是不是官方说法)。如果 class 的 用法 是在调用 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 时,该属性不存在。正如您在自己的评论中所说,"they spring into existence when they are first assigned to."

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.

你的导师错了,或者你误解了他们的意思。在您给出的示例中,每辆汽车都具有相同的初始 speedtime。通常,__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

然后您可以使用 c = Car(3, 5) 初始化 Car。如果可选,则将默认值放入 init 中。

编辑:改编示例 from the 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'