-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 ?

martineau
  • 119,623
  • 25
  • 170
  • 301
Kaushik
  • 553
  • 3
  • 11
  • 27
  • Even though you mentioned java, this question is totally unrelated to it – SomeJavaGuy Aug 11 '16 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 – dnit13 Aug 11 '16 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`. – khelwood Aug 11 '16 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. – Torben Klein Aug 11 '16 at 15:35

1 Answers1

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 ... }
Torben Klein
  • 2,943
  • 1
  • 19
  • 24