简体   繁体   English

在__dict__中找不到python中的类变量

[英]Class variables in python not found in __dict__

There is a code: 有一个代码:

class C():
    a=1
    def f(self):
        print "f func"

a=C()
print a.a
a.f()
>>> 1
>>> f func

And when i trying to get a.__dict__ or vars(a) , it shows me just {} . 当我尝试获取a.__dict__vars(a) ,它只显示{} But

a.b=123
print a.__dict__
>>> {'b': 123}

I don't understand, why it is. 我不明白,为什么会这样。

Looking at a.__dict__ or vars(a) gives you attributes of a , which is an instance. 查看a.__dict__vars(a)会为您提供a属性,它是一个实例。 That instance initially has no attributes of its own. 该实例最初没有自己的属性。 The attribute a that you created in your class definition is an attribute of the class itself, not of its instances. 您在类定义中创建的属性a是类本身的属性,而不是其实例的属性。 Later when you do ab = 123 , you create an attribute just on the instance, so you can see it in the instance __dict__ . 稍后,当您执行ab = 123 ,仅在实例上创建一个属性,因此您可以在实例__dict__看到它。 You will see the attribute a if you look at C.__dict__ . 如果查看C.__dict__将看到属性a

When you do print aa , Python dynamically finds the attribute a on the class C . 当您print aa ,Python动态地在类C上找到属性a It sees that the instance doesn't have an attribute a , so it looks on the class and finds one there. 它看到实例没有属性a ,因此它在类上查找并在其中找到一个。 That is the value that is printed. 那就是打印的值。 The class attribute is not "copied" to the instance when the instance is created; 创建实例时,class属性不会“复制”到实例。 rather, every individual time you try to read the instance attribute, Python checks to see if it exists on the instance, and if not it looks it up on the class. 相反,每当您尝试读取实例属性时,Python都会检查该实例属性是否存在,如果不存在,则会在类中进行查找。

>>> C.a
1
>>> vars(C)['a']
1

(The whole vars dictionary for a class is rather long.) (一个类的整个vars字典相当长。)

Like your title says, it's a class variable. 如标题所示,它是一个类变量。 It belongs to the class, not the object. 它属于类,而不是对象。 Python is doing some special logic behind the scenes to look on the type object for you when you call aa . Python在幕后做一些特殊的逻辑,以便在您调用aa时为您查找类型对象。 I'm not an expert, but I suspect it's finding a the same way it would find a method. 我不是专家,但我怀疑这是找到a同样的方式,它会找到一个方法。 In languages such as Java, I believe this sort of usage is discouraged. 我相信在Java之类的语言中,不建议使用这种用法。 I don't know if it's discouraged in Python. 我不知道它是否不建议在Python中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM