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

时间:2015-01-27 01:12:01

标签: python namespaces python-2.x

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

我对Python中的命名空间有疑问:

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

a = Team()
a.p()

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

在Java中,它将类似于:

class Team()
{
    int x = 2;
}

a = new Team();

2 个答案:

答案 0 :(得分:5)

如果您想要实例属性并且默认值为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

答案 1 :(得分:1)

如果你想把make x作为类变量,那就试试这个:

class Team(object):
    x = 2 
    def __init__(self):
      pass

print Team.x
Team.x = 3
print Team.x

您不需要实例来获取价值,您可以根据需要进行更改。

如果你想将num作为实例属性,你必须使用self(在Java中这样):

class Team(object):

  def __init__(self, num):
    self.num = num

  def get_num(self):
    return self.num

  def set_num(self, change_num):
    self.num = change_num

t1 = Team(2)
print t1.get_num()
t1.set_num(3)
print t1.get_num()