1

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();
1
  • 4
    you should be calling it as self.x Commented Jan 27, 2015 at 1:12

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

why didnt you create x at the class level ? solid answer none the less (ahh the edit makes it more clear that you are probably correctly anticipating his use case)
@JoranBeasley, I was going to link to an answer showing the difference between class an instance attributes, I just thought doing it this way was more obvious.
Quick note, you may want to inherit from object since this is on python2.x
Don't forget object in Python 2, old-style classes are rarely used.
I guess I really needed to add object :)
|
1

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

1 Comment

Do you need init explicitly if it's just passing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.