python类的属性不在__init__中 [英] python class's attribute not in __init__

查看:84
本文介绍了python类的属性不在__init__中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下代码为何起作用?

I want to know why the following codes work?

#!/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 中,如下所示.

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.

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

如果有一些官方文件可以解释,那会更好.

If there are some official documents can explain this would be better.

推荐答案

它是类属性vs实例属性vs动态属性.当您这样做时:

It's class attributes vs instance attributes vs dynamic attributes. When you do:

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

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

speed time 是动态属性(不确定这是否是正式术语).如果此类的 usage 使得在调用 Car 的任何其他方法之前设置了这些属性,则这些方法可以使用 self.speed .否则,您会得到一个错误:

speed and time are dynamic attributes (not sure if this is an official term). If the usage of the class is such that these attributes are set before calling any other methods of Car, then those methods can use self.speed. Otherwise, you get an error:

>>> 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 时,该属性不存在.正如您在自己的评论中所说的,它们在首次分配给它们时就已存在."

This happens because for c, speed and time are attributes on that instance of Car. Their existence or value doesn't propagate across other instances of Car. So when I create d and then try to lookup d.speed, the attribute doesn't exist. As you've said in your own comment, "they spring into existence when they are first assigned to."

我意外地发现我不必在init中使用init属性.我从每位导师那里学习,我必须像下面那样将作业放在init中.

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 time .通常, __ init __ 看起来像这样:

Your tutors were very wrong or you misunderstood what they meant. In the example you gave, every Car gets the same initial speed and time. Typically, an __init__ would look like this:

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中.

You can then initialise a Car with: c = Car(3, 5). Or put default values in init if it's optional.

从文档中 改编的示例:

example adapted 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__中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆