为什么我的实例变量不在__dict__中?

时间:2022-09-11 18:11:36

If I create a class A as follows:

如果我按如下方式创建A类:

class A:
    def __init__(self):
        self.name = 'A'

Inspecting the __dict__ member looks like {'name': 'A'}

检查__dict__成员看起来像{'name':'A'}

If however I create a class B:

但是,如果我创建了一个B类:

class B:
    name = 'B'

__dict__ is empty.

__dict__是空的。

What is the difference between the two, and why doesn't name show up in B's __dict__?

这两者有什么区别,为什么名字不会出现在B的__dict__中?

2 个解决方案

#1


44  

B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__.

B.name是类属性,而不是实例属性。它出现在B .__ dict__中,但不出现在b = B()中; b .__ dict__。

The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.

这种区别有些模糊,因为当您访问实例上的属性时,类dict是一个后备。所以在上面的例子中,b.name将为您提供B.name的值。

#2


12  

class A:
    def _ _init_ _(self):
        self.name = 'A'
a = A()

Creates an attribute on the object instance a of type A and it can therefore be found in: a.__dict__

在类型A的对象实例a上创建一个属性,因此可以在以下位置找到:a .__ dict__

class B:
    name = 'B'
b = B()

Creates an attribute on the class B and the attribute can be found in B.__dict__ alternatively if you have an instance b of type B you can see the class level attributes in b.__class__.__dict__

在B类上创建一个属性,该属性可以在B .__ dict__中找到,或者如果你有一个B类实例b,你可以在b .__ class __.__ dict__中看到类级属性。

#1


44  

B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__.

B.name是类属性,而不是实例属性。它出现在B .__ dict__中,但不出现在b = B()中; b .__ dict__。

The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.

这种区别有些模糊,因为当您访问实例上的属性时,类dict是一个后备。所以在上面的例子中,b.name将为您提供B.name的值。

#2


12  

class A:
    def _ _init_ _(self):
        self.name = 'A'
a = A()

Creates an attribute on the object instance a of type A and it can therefore be found in: a.__dict__

在类型A的对象实例a上创建一个属性,因此可以在以下位置找到:a .__ dict__

class B:
    name = 'B'
b = B()

Creates an attribute on the class B and the attribute can be found in B.__dict__ alternatively if you have an instance b of type B you can see the class level attributes in b.__class__.__dict__

在B类上创建一个属性,该属性可以在B .__ dict__中找到,或者如果你有一个B类实例b,你可以在b .__ class __.__ dict__中看到类级属性。