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

1
  • What happens when you try it? Commented Oct 12, 2014 at 21:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.