Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run a method for all instances of a class in python?

Example code:

>>> class MyClass(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def power(self):
            print(self.x**self.y)
        def divide(self):
            print(self.x/self.y)

>>> foo = MyClass(2, 3)
>>> bar = MyClass(4, 7)
>>> 
>>> foo.power()
8
>>> bar.divide()
0.5714285714285714

Whenever I used classes in Python previously, I just ran the method for each instance separately (see above). I was just wondering If there was a way to run the same method for all the instances of that class at once, because it could get a bit annoying, if you have 20 or so instances. I'm thinking of something like this:

>>> allinstances.power()
8
16384

Is there a way of doing this?

like image 862
jakoubeck503 Avatar asked Dec 01 '22 17:12

jakoubeck503


2 Answers

class MyClass(object):

    instancelist = []

    def __init__(self, x, y):
        self.x = x
        self.y = y
        MyClass.instancelist.append(self)

    def power(self):
        print(self.x ** self.y)

    def divide(self):
        print(self.x / self.y)


foo = MyClass(2, 3)
bar = MyClass(4, 7)

[instance.power() for instance in MyClass.instancelist]

will output:

8
16384

This way you do not need any global variables or placeholders that are stored outside of the class definition.

like image 194
Holy Mackerel Avatar answered Jan 19 '23 00:01

Holy Mackerel


Not usually. You could make your class be capable of that, however:

GLOBAL_MYCLASS_LIST = []

class MyClass(object):

    def __init__(self, x, y):
        GLOBAL_MYCLASS_LIST.append(self)
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

a = MyClass(2, 3)
b = MyClass(4, 7)
all_powers = [i.power() for i in GLOBAL_MYCLASS_LIST]

Of course, you could also do that without baking it into the class, which is probably cleaner for most cases where you might have different sets of MyClasses:

myclass_list = []

class MyClass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

myclass_list.append(MyClass(2, 3))
myclass_list.append(MyClass(4, 7))
all_powers = [i.power() for i in myclass_list]
like image 28
Amber Avatar answered Jan 18 '23 23:01

Amber