-1

I am moving from Java to Python. In Java, Static variables will return the same value to all objects of a class even if it is changed by another object of the same class. In the Python book that I'm reading, the author says, a data member is entered into class namespace if it's assignment takes place within the immediate scope of the class definition.

I'm using IDLE, the Python Interpreter, and below is the Python code:

class ABC:
    OVRLIMIT_FEE=5

>>> a=ABC()
>>> b=ABC()

>>> a.OVRLIMIT_FEE+=1
>>> a.OVRLIMIT_FEE
6
>>> b.OVRLIMIT_FEE
5

But if it enters the class namespace, should it not return same value when it is accessed with both a and b ?

4
  • Even though you mentioned java, this question is totally unrelated to it Commented Aug 11, 2016 at 11:05
  • 1
    you are changing an objects attribute not ABC's attribute, do ABC.OVRLIMIT_FEE+=1 then you will get 6 for both Commented Aug 11, 2016 at 11:06
  • If you assign to a.OVRLIMIT_FEE (as you have done with a.OVRLIMIT_FEE+=1), you are creating an instance variable on a. If you want to access a class variable, use ABC.OVRLIMIT_FEE. Commented Aug 11, 2016 at 11:06
  • Why is this marked as duplicate? The referenced question asks about existence of "static" variables, this one about a specific behaviour of them. Admittedly the answers cover this problem as well. Commented Aug 11, 2016 at 15:35

1 Answer 1

0

What happens is that you created a so-called Oldstyle class, which does not support your (correctly) expected behaviour. Inherit from object to create a new-style class. Then it will work as you expect [...]

Using a.foo += 1 is implicitly unterstood as a.foo = a.foo + 1, which

  • takes the class property foo
  • adds 1
  • puts the result into instance property foo.

Code:

>>> class B(object):
...   x=5
>>> b1=B()
>>> b2=B()
>>> b1.x += 1
>>> b1.__dict__
{'x': 6}
>>> b2.__dict__
{}
>>> B.__dict__
{'x': 5  ... and other stuff ... }
Sign up to request clarification or add additional context in comments.

2 Comments

b2.x prints 6 because x is 6 for class B. If it is to work as I expect, should it not print 7 ?
oh my, I should not answer python questions in the lunch break.. I will correct the answer right away.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.