gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:18:33 25 4
gpt4 key购买 nike

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

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_class.crunch_all() 应该向所有现有实例添加一个新属性 new_value。我猜我将不得不使用 @staticmethod 使其成为“全局”函数。

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

最佳答案

在初始化时向类注册对象(即__init__)并定义一个类方法(即@classmethod) 对于类(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

例子:

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

关于python - 将函数应用于类的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com