python 类的属性不在 __init__ 中

标签 python class variable-assignment

我想知道以下代码为何有效?

#!/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 Car():
    def __init__(self):    
        pass

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

速度时间是动态属性(不确定这是否是官方术语)。如果该类的用法是在调用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 实例的属性。它们的存在或值(value)不会在 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.

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

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

关于python 类的属性不在 __init__ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710765/

相关文章:

python - 如何使用pycaffe重构caffe net

python - 无法在ubuntu上运行python3

java - 从运行时加载的 java 9 模块加载类时出现 ClassNotFoundException

c++ - 这是实现错误处理的安全方法吗?

python - pandas 中按组的值计数

python - 如何获取边界框区域内热图的平均值

php - 从父抽象类调用抽象方法

r - 将yyyymmdd字符串转换为R中的Date类

algorithm - 详细的匈牙利算法(分配问题)问题

python - 将项目列为变量分配