n1000
n1000

Reputation: 5314

Apply a function to all instances of a class

I am looking for a way to apply a function to all instances of a class. An example:

class my_class:

    def __init__(self, number):
        self.my_value = number
        self.double = number * 2

    @staticmethod
    def crunch_all():
        # pseudocode starts here
        for instances in my_class:
             instance.new_value = instance.my_value + 1

So the command my_class.crunch_all() should add a new attribute new_value to all existing instances. I am guessing I will have to use @staticmethod to make it a "global" function.

I know I could keep track of the instances that are being defined by adding something like my_class.instances.append(number) in __init__ and then loop through my_class.instances, but I had no luck so far with that either. Also I am wondering if something more generic exists. Is this even possible?

Upvotes: 2

Views: 5408

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77961

Register objects with the class at initialisation (i.e. __init__) and define a class method (i.e. @classmethod) for the class:

class Foo(object):
    objs = []  # registrar

    def __init__(self, num):
        # register the new object with the class
        Foo.objs.append(self)
        self.my_value = num

    @classmethod 
    def crunch_all(cls):
        for obj in cls.objs:
            obj.new_value = obj.my_value + 1

example:

>>> a, b = Foo(5), Foo(7)
>>> Foo.crunch_all()
>>> a.new_value
6
>>> b.new_value
8

Upvotes: 9

Related Questions