Class Variable Vs. Instance Variable In Python For Int Value
Solution 1:
In the first example,
self.d = self.d + 1
rebinds self.d
, making it independent of test.d
.
In the second example,
self.d.append("1")
modifies test.d
.
To see that for yourself, print id(self.d)
at the end of both constructors.
If you modified the second example to match the first:
self.d = self.d + ["1"]
you'd see that the behaviour would also change to match.
Solution 2:
If you want to modify a class variable, do:
class test(object):
d=0
def __init__(self):
type(self).d=self.d+1;
D=test()
print D.d
D1=test()
print D1.d
D2=test()
print D2.d
You don't need the type
on the right hand side of the assignment, because this way you never create an instance variable d
. Note that new-style classes are necessary to this.
type
is a function (actually a callable - it is also a class; but don't worry about that for now) which returns the class of its argument. So, type(self)
returns the class of self
. Classes are first class objects in Python.
Demo here: http://ideone.com/JdNpiV
Update: An alternative would be to use a classmethod
.
Solution 3:
To address a class variable use class_name.variable_name, giving :
class test(object):
d=0
def __init__(self):
test.d = test.d + 1;
Solution 4:
NPE's answer tells you what is going wrong with your code. However, I'm not sure that it really tells you how to solve the issue properly.
Here's what I think you want, if each test
instance should have a different d
value in an instance variable:
class test(object): # new style class, since we inherit from "object"
_d = 0 # this is a class variable, which I've named _d to avoid confusion
def __init__(self):
self.d = test._d # assign current value of class variable to an instance variable
test._d += 1 # increment the class variable
Now, you can create multiple instances and each one will get a unique value for d
:
>>> D0 = test()
>>> D1 = test()
>>> D2 = test()
>>> print D0.d
0
>>> print D1.d
1
>>> print D2.d
2
Post a Comment for "Class Variable Vs. Instance Variable In Python For Int Value"