-2

Is it possible in Python make a static attribute of class which will be same for all instances (objects) of that class, they all will use same reference to that attribute without creating their own attributes.

For example :

class myClass:
    __a = 0

    def __init__(self, b, c):
        self.b = b
        self.c = c

    def increase_A(self):
        self.__a += 1
        return

    def get_A(self):
        return self.__a

So if I have

myObject1 = myClass(1,2)
myObject2 = myClass(3,4)

myObject2.increase_A()

print myObject1.get_A()  

will show one and not zero, couse they share the same variable ?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
fpopic
  • 1,756
  • 3
  • 28
  • 40

2 Answers2

3

To make your code work as it appears you intend, use myClass.__a to access the variable, instead of self.__a.

def increase_A(self):
    myClass.__a += 1
    return

def get_A(self):
    return myClass.__a
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
3

They start off as the same variable. However, when you do

self.__a += 1

this rebinds the object's __a to a new object whose value is 1.

It does not change any other object's __a so the code will print out 0.

NPE
  • 486,780
  • 108
  • 951
  • 1,012