python - 如何在 Python 的初始化程序中访问类变量?

标签 python scope python-2.x

我认为 Python 中的 class 语句会创建一个范围。但是尝试这个简单的代码我得到了一个错误:

class A():
    foo = 1 
    def __init__(self):
        print foo 

a = A() 

NameError: global name 'foo' is not defined

为什么 foo 不能从初始化器访问?访问它的正确方法是什么?

最佳答案

创建作用域。这记录在 pep 227 中:

Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope. If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions.

并且在 class compound statement documentation :

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [4] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

强调我的;执行框架是一个临时范围。

要访问 foo,请使用 self.foo:

class A():
    foo = 1 
    def __init__(self):
        print self.foo 

或按名称访问A类,或使用type(self)访问当前类(可以是子类) :

def __init__(self):
    print A.foo 

def __init__(self):
    print type(self).foo 

关于python - 如何在 Python 的初始化程序中访问类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16980804/

相关文章:

python - django-rest-swagger : how to group endpoints?

c++ - 处理大量变量声明

javascript - switch/case 语句中的 JavaScript 变量作用域是什么?

python - 为什么在打印时比较这两个日期在 python 中失败,它们是相同的

python - 如何在不引发 UnicodeEncodeError 的情况下覆盖 str 函数?

python - 使用 numpy 从 csv 加载一定数量的行

python - 使用正则表达式添加空组

python - PyQt5 线程、信号和槽。连接错误

IOS Objective-C 选择器使用了错误的范围

python - 在巨大的字符串中执行增量正则表达式搜索 (Python)