Skip to main content
 首页 » 编程设计

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

2025年05月04日13findumars

我认为 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