我有一个带有一些内置方法的类。这是类的抽象示例:
class Foo:
def __init__(self):
self.a = 0
self.b = 0
def addOneToA(self):
self.a += 1
def addOneToB(self):
self.b += 1
为了简单起见,我已经将内置方法减少到总共2个,但实际上我的类接近20个
接下来,我有另一个类,它设计用于处理Foo
实例列表
class Bar:
def __init__(self, fooInstances):
self.fooInstances = fooInstances
# Bar([Foo(), Foo(), Foo()])
如果我想将其中一个Foo
方法应用于Bar
中的Foo
实例,该怎么办
class Bar:
# ...
def addOneToA(self):
for fooInstance in self.fooInstances:
fooInstance.addOneToA()
def addOneToB(self):
for fooInstance in self.fooInstances:
fooInstance.addOneToB()
上面的例子是我所描述的一种方法,但是如果有20个Foo
类方法,那么这样做似乎需要大量重复的代码。或者,我可以这样做:
class Bar:
# ...
def applyFooMethod(self, func, *args):
for fooInstance in self.fooInstances:
fooInstance.func(args)
但是我更希望有一些东西可以让我在Bar
上调用.addOneToA()
,并将其应用于Bar
中的所有Foo
实例。有没有一种干净的方法可以做到这一点,而不必在Bar
内部定义所有的Foo
方法
一种方法是覆盖
Bar
的__getattr__
:如果对
Bar
对象的属性查找失败,则调用__getattr__
上的Bar
。然后,我们尝试查看Foo
实例是否具有该属性;如果不是,则引发AttributeError
,因为Bar
和Foo
都不接受该属性。但是,如果Foo
确实有它,我们将返回一个函数,当调用该函数时,在Bar
对象中的Foo
的每个瞬间调用方法(attr
)用法:
另一种方法是使用
setattr()
创建一个函数,在构造bar
对象时调用applyFooMethod()
。这样,dir(bar)
将显示Foo
的方法然后,您可以这样运行它:
现在,我们可以调用
bar.addOneToA()
:它首先递增所有
a
值,然后递增所有b
值相关问题 更多 >
编程相关推荐