Tuesday 15 April 2014

python - Apply a function to all instances of a class -



python - Apply a function to all instances of a class -

i looking way apply function instances of class. example:

class my_class: def __init__(self, number): self.my_value = number self.double = number * 2 @staticmethod def crunch_all(): # pseudocode starts here instances in my_class: instance.new_value = instance.my_value + 1

so command my_class.crunch_all() should add together new attribute new_value existing instances. guessing have utilize @staticmethod create "global" function.

i know maintain track of instances beingness defined adding my_class.instances.append(number) in __init__ , loop through my_class.instances, had no luck far either. wondering if more generic exists. possible?

register objects class @ initialisation (i.e. __init__) , define class method (i.e. @classmethod) class:

class foo(object): objs = [] # registrar def __init__(self, num): # register new object class foo.objs.append(self) self.my_value = num @classmethod def crunch_all(cls): 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

python class

No comments:

Post a Comment