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

Python 将函数应用于类的所有实例,python,class,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:

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

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
因此,命令
my\u class.crunch\u all()
应该向所有现有实例添加一个新属性
new\u value
。我猜我将不得不使用
@staticmethod
使其成为一个“全局”函数

我知道我可以通过在
\uuuu init\uuuu
中添加类似
my\u class.instances.append(number)
的内容来跟踪正在定义的实例,然后循环查看
my\u class.instances
,但到目前为止我也没有运气。我还想知道是否存在更一般的东西。这可能吗?

在初始化时向类注册对象(即
\uuuu init\uuuu
),并为类定义类方法(即
@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
例如:

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

它应该是
@classmethod
,而不是
@staticmethod
。是的,您必须在class属性中跟踪类的所有实例。你可以看到
id(Foo.objs)
id(a.objs)
id(b.objs)
都是指同一件事。因此,如果有人想这样做,他们可以做一些讨厌的事情,比如
a.objs.append(“hello”)
,现在
crunch\u all
将有一个错误,因为
objs
末尾的字符串没有
my\u value
属性可访问。因为这是在
objs
的内容发生变异时发生的(完全重新分配时,
\uuuuu setattr\uuuu
序列只对
a
发生,其他人不发生)您只需将
objs
a
tuple
制作成一个
tuple,这样它就不会被变异,然后在构造函数中,从旧的
tuple的内容中创建一个新的
tuple
,并添加正在创建的实例。这是一个有用的相关问题:<>。