简体   繁体   English

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

[英]How do I reference the variable declared under a class in Python?

I am relatively new to Python and I am using Python 2.7.x 我对Python相对较新,正在使用Python 2.7.x

I have a question regarding namespaces in Python: 我对Python中的名称空间有疑问:

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

a = Team()
a.p()

When I run the code, it says global x is not defined . 当我运行代码时,它说global x is not defined Shouldn't x belong to the Team object? x不应该属于Team对象吗? My goal is to create a Team class where x has a default value of 2. 我的目标是创建一个Team类,其中x的默认值为2。

In Java it would be something like: 在Java中,它将类似于:

class Team()
{
    int x = 2;
}

a = new Team();

If you want an instance attribute and a default value of 2 : 如果您想要实例属性和默认值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

Difference between class vs instance attributes 类与实例属性之间的区别

new vs old style classes 新旧样式类

If you want make x as class variable, just try this way: 如果要将x作为类变量,只需尝试以下方法:

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

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

You don't need to instance to get the value and you can change it as you want. 您无需实例即可获取值,并且可以根据需要更改它。

If you want to make the num as instance property, you have to use self(like this in Java): 如果要将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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM