Python类变量名vs __name__ [英] Python class variable name vs __name__
问题描述
我试图理解一个Python类对象赋值的变量和该类对象的 __ name __
属性之间的关系。例如:
I'm trying to understand the relationship between the variable a Python class object is assigned to and the __name__
attribute for that class object. For example:
In [1]: class Foo(object):
...: pass
...:
In [2]: Foo.__name__ = 'Bar'
In [3]: Foo.__name__
Out[3]: 'Bar'
In [4]: Foo
Out[4]: __main__.Bar
In [5]: Bar
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-962d3beb4fd6> in <module>()
----> 1 Bar
NameError: name 'Bar' is not defined
似乎我已经改变了 __ name __
属性的类,但我不能通过该名称引用它。我知道这有点一般,但可以有人解释 Foo
和 Foo .__ name __
?之间的关系?
So it seems like I have changed the __name__
attribute of the class but I can't refer to it by that name. I know this is a bit general but could someone explain the relationship between Foo
and Foo.__name__
?
推荐答案
很简单。
创建一个类时,将使用您所使用的名称创建一个局部变量,指向类,以便您可以使用它。
When you create a class a local variable is created with name you used, pointing at the class so you can use it.
该类还会获得一个属性 __ name __
,其中包含该变量的名称,因为在某些情况下,
The class also gets an attribute __name__
that contains the name of that variable, because that's handy in certain cases, like pickling.
您可以将局部变量设置为其他值,或者更改 __ name __
变量,不工作,所以不要这样做。
You can set the local variable to something else, or change the __name__
variable, but then things like pickling won't work, so don't do that.
这篇关于Python类变量名vs __name__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!