aceminer
aceminer

Reputation: 4295

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

I have a question regarding namespaces in 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. Shouldn't x belong to the Team object? My goal is to create a Team class where x has a default value of 2.

In Java it would be something like:

class Team()
{
    int x = 2;
}

a = new Team();

Upvotes: 1

Views: 156

Answers (2)

lqhcpsgbl
lqhcpsgbl

Reputation: 3792

If you want make x as class variable, just try this way:

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):

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()

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

If you want an instance attribute and a default value of 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

Upvotes: 5

Related Questions