将函数应用于类的所有实例

n10*_*000 2 python class

我正在寻找一种方法将函数应用于类的所有实例.一个例子:

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
Run Code Online (Sandbox Code Playgroud)

因此该命令my_class.crunch_all()应该new_value为所有现有实例添加新属性.我猜我将不得不使用@staticmethod它来使它成为一个"全局"功能.

我知道我可以通过添加类似my_class.instances.append(number)的内容__init__然后循环来跟踪正在定义的实例my_class.instances,但到目前为止我也没有运气.另外,我想知道是否存在更通用的东西.这甚至可能吗?

beh*_*uri 6

在初始化(即__init__)时使用类注册对象,并为类定义类方法(即@classmethod):

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
Run Code Online (Sandbox Code Playgroud)

例:

>>> a, b = Foo(5), Foo(7)
>>> Foo.crunch_all()
>>> a.new_value
6
>>> b.new_value
8
Run Code Online (Sandbox Code Playgroud)