4

I am new to python and i am not sure how this is working. Code is as below:

class test():
    d=0
    def __init__(self):
       self.d=self.d+1;

D=test()
print D.d
D1=test()
print D1.d
D2=test()
print D2.d

Output is

1,1,1  # This should not be

Now using this :

class test():
    d=[]
    def __init__(self):
       self.d.apend("1");

 D=test()
 print D.d
 D1=test()
 print D1.d
 D2=test()
 print D2.d

Result is (This should be)

['1']
['1', '1']
['1', '1', '1']

So i am not sure why integer value is not being treated as class variable while list is being treated.

3
  • Why are you using old style classes? Commented Jun 29, 2013 at 14:38
  • @spgc I am new, pls tell me new style. Commented Jun 29, 2013 at 14:45
  • See my answer. It covers this. Commented Jun 29, 2013 at 14:46

4 Answers 4

3

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.

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

4 Comments

why it is modifying in second and not in first. I guess it should work same in both case as per operator used.
@bimleshsharma It's not the same operator. One is assigning, one is not.
@Marcin Yes, ID is different.
@bimleshsharma I am not sure what you are trying to tell me with this comment.
3

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.

Comments

0

To address a class variable use class_name.variable_name, giving :

class test(object):
    d=0
    def __init__(self):
       test.d = test.d + 1;

8 Comments

(a) x = self.d will address the class variable d if the name is not shadowed by an instance variable (b) this is not the only method of assigning to a class variable (c) this is a bad way of assigning to a class variable, because if the class name changes, you will need to alter all references to the name.
It is actually wrong in that it falsely implies that x = self.d would not work. Your "fix" which you advocate because you did not know that is also bad practice.
@marcin. Sorry I do not understand your example with x = self.d. Can you update my code to show it?
What don't you understand? See NPE's answer.
I understand it is bad coding practice, But I do not understand from your comment why my solution worked and the syntax is allowed?
|
0

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

Comments

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.