python 实例方法不执行_有没有一种方法可以在python中为类的所有实例运行方法?...

Example code:

>>> 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

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]

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值