Maintaining a common value of a static variable across instances in Python

496 views Asked by At

I have read that to create a static variable we can declare them inside the class definition and not inside the method. But it doesn't seem so "static" to me when looked at from Java world since changing a variable's value from one instance creates its own variable different from the class variable. I'm looking for a way to ensure that the value of a variable remains consistent across different instances. One of the answers on StackOverflow had suggested the following piece of code which doesn't seem to work well for me.

class Test(object):
_i = 3
@property
def i(self):
    return self._i
@i.setter
def i(self,val):
    self._i = val


x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # The example suggested no error here but it doesn't work for me

Can you explain with an example if it's possible to achieve this?

1

There are 1 answers

3
AudioBubble On BEST ANSWER
class Test(object):
    _i = 3

    @classmethod
    def set_i(self, value):
        self._i = value

    def get_i(self):
        return self._i

    i = property(get_i, set_i)

x1 = Test()
x2 = Test()
print(x1.i) # 3
print(x2.i) # 3

x1.set_i(50)
print(x1.i) # 50
print(x2.i) # 50