classinstance .__ dict__返回空字典

时间:2016-06-06 07:00:17

标签: python class dictionary

当我定义一个已经赋值变量的类时,实例化它并使用__dict__将变量作为字典获取,我得到一个空列表。

In [5]:

class A(object):
    a = 1
    b = 2
    text = "hello world"

    def __init__(self):
        pass

    def test(self):
        pass

x = A()
x.__dict__

Out[5]:
{}

但是当我在__init__中声明变量并使用__dict__时,它会返回在实例化类之后分配的变量。

In [9]:

class A(object):
    a = 1
    def __init__(self):
        pass

    def test(self):
        self.b = 2
        self.text = "hello world"


x = A()
x.test()
x.__dict__

Out[9]:
{'b': 2, 'text': 'hello world'}

为什么__dict__只返回在实例化类

之后声明的变量

修改答案

创建实例时,如x = A()

x.__dict__存储所有实例属性。

A.__dict__存储类属性

1 个答案:

答案 0 :(得分:1)

请尝试A.__dict__获取所有类属性,

x = A()
x.__dict__

这里你在A&#39实例上调用__dict__方法。因此,应显示与该实例关联的变量......

self.bself.text是特定于特定实例的实例变量。

相关问题