Skip to main content
 首页 » 编程设计

python之如何在python中创建一个可调用的函数数组

2025年05月04日23telwanggs

我正在尝试创建一个类 A,它基本上是对象 B 的列表。 我希望能够自动调用 A 中的方法 返回 B 中相应方法的列表:

A.method(x) = [B.method(x) for B in A]

问题是我需要动态行为,所以 B 中的任何方法都是 由 A 自动“继承”,而无需对其进行硬编码。

我尝试过使用 lambda 函数和 exec("""def ..."""), 但似乎没有任何效果。这是一个尝试:

class A(object): 
 
    def __init__(self,Bs): 
        self.listOfBs = Bs[:] 
 
        if self.listOfBs: 
            for method_name in dir(self.listOfBs[0]): 
                if not callable(getattr(self.listOfBs[0],method_name)): 
                    continue 
 
            f = lambda x: [getattr(B,method_name)(x) for B in self.listOfBs] 
            setattr(self,method_name,f) 
 
class B(object): 
    def __init__(self,name): 
 
        self.name = name 
 
    def getName(self,x): 
        return self.name+x 
 
#So if I define: 
a = A([B('x'),B('y'),B('z')]) 
 
#I would like to have: a.getName('W') = ['xW','yW','zW'] 
#However I get the error: TypeError: 'str' object is not callable 

我认为应该有一种简单/优雅的方法可以在 python 中实现上述行为,但我找不到任何有效的方法。

请您参考如下方法:

您可以使用__getattr__ 使方法查找动态化

class A: 
    def __init__(self, bs): 
        self.bs = bs 
 
    def __getattr__(self, method_name): 
        def call(*args, **kw): 
            return [getattr(b, method_name)(*args, **kw) for b in bs] 
        return call