有没有一种方法可以在python中为类的所有实例运行方法? [英] Is there a way to run a method for all instances of a class in python?

查看:327
本文介绍了有没有一种方法可以在python中为类的所有实例运行方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码:

>>> class MyClass(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def power(self):
            print(self.x**self.y)
        def divide(self):
            print(self.x/self.y)

>>> foo = MyClass(2, 3)
>>> bar = MyClass(4, 7)
>>> 
>>> foo.power()
8
>>> bar.divide()
0.5714285714285714

每当我以前在Python中使用类时,我都会分别为每个实例运行方法(请参见上文).我只是想知道是否有一种方法可以一次为该类的所有实例运行相同的方法,因为如果您有20个左右的实例,它可能会令人讨厌.我在想这样的事情:

Whenever I used classes in Python previously, I just ran the method for each instance separately (see above). I was just wondering If there was a way to run the same method for all the instances of that class at once, because it could get a bit annoying, if you have 20 or so instances. I'm thinking of something like this:

>>> allinstances.power()
8
16384

有没有办法做到这一点?

Is there a way of doing this?

推荐答案

通常不会.您可以使自己的班级有能力做到这一点,但是:

Not usually. You could make your class be capable of that, however:

GLOBAL_MYCLASS_LIST = []

class MyClass(object):

    def __init__(self, x, y):
        GLOBAL_MYCLASS_LIST.append(self)
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

a = MyClass(2, 3)
b = MyClass(4, 7)
all_powers = [i.power() for i in GLOBAL_MYCLASS_LIST]

当然,您也可以不将其烘烤到类中而这样做,对于大多数情况下,您可能会有不同的MyClass es集:

Of course, you could also do that without baking it into the class, which is probably cleaner for most cases where you might have different sets of MyClasses:

myclass_list = []

class MyClass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

myclass_list.append(MyClass(2, 3))
myclass_list.append(MyClass(4, 7))
all_powers = [i.power() for i in myclass_list]

这篇关于有没有一种方法可以在python中为类的所有实例运行方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆