Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change all objects of a class at once?

Tags:

python

oop

I am rediscovering OOP through a GUI application I am writing and would like to understand if it is possible to change a characteristic of all objects instantiated from a class. I have the following code:

class myclass():
    def __init__(self):
        self.a = 1

x = myclass()
y = myclass()
print x.a, y.a  # outputs 1 1
# the instruction I am looking for, assigns 2 to a in each object at once
print x.a, y.a  # outputs 2 2

What I am looking for is a way to change x and y at once by manipulating the parent class. I know that I can have a method which modifies self.a - I do not want to use that because it means I have to call it separately for each object.

My gut feeling is that this is not possible and that I have to cleverly handle my objects to simplify such activities (for instance by storing them in a list I would loop over, applying a method). I just do not want to miss a mechanism which I am not aware of and which would greatly simplify my code.

like image 669
WoJ Avatar asked Dec 15 '22 21:12

WoJ


1 Answers

You can have all instances share a variable if you define it as a class variable:

>>> class myclass():
...     a = 1
...     def __init__(self):
...         self.b = 2
...
>>> x = myclass()
>>> y = myclass()
>>> x.a
1
>>> myclass.a = 2   # modify the class variable
>>> x.a
2
>>> y.a
2
>>> x.b = 3         # modify the instance variable
>>> x.b
3
>>> y.b
2
>>> x.a = 4         # create new local instance variable a
>>> x.a
4
>>> y.a
2

Note that now if you change myclass.a, you won't see the change in x because the instance variable will be looked up before the class variable - until you remove the instance variable using del:

>>> myclass.a = 3
>>> x.a
4
>>> y.a
3
>>> del x.a
>>> x.a
3
like image 145
Tim Pietzcker Avatar answered Dec 27 '22 06:12

Tim Pietzcker