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();
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
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.