Skip to main content
 首页 » 编程设计

python之如何引用在 Python 中的类下声明的变量

2025年05月04日15jackei

我是 Python 的新手,我使用的是 Python 2.7.x

我有一个关于 Python 命名空间的问题:

class Team(): 
    x = 2  
    def p(self): 
        print x  
 
a = Team() 
a.p() 

当我运行代码时,它说 global x is not defined。 x 不应该属于 Team 对象吗?我的目标是创建一个 Team 类,其中 x 的默认值为 2。

在 Java 中它会是这样的:

class Team() 
{ 
    int x = 2; 
} 
 
a = new Team(); 

请您参考如下方法:

如果你想要一个实例属性和默认值 2 :

class Team(object): # use object for new style classes  
    def __init__(self, x=2): 
        self.x = x # use self to refer to the instance 
 
    def p(self): 
        print self.x # self.x  
 
a = Team() 
a.p() 
2 
 
b = Team(4) # give b a different value for x 
b.p() 
4 

class vs instance attributes 之间的区别

new vs old style classes