Python 将对象的方法添加到包含列表

Python add methods of objects to containing list

我有一个包含相同 class 对象的列表。现在我想让该列表成为一个容器 class,它与它包含的对象的所有方法相关,正如您在下面的示例中看到的那样。但是由于我有很多方法,所以我不想再像这样在包含容器-class中显式写下它们:

模块fe.py

class foo:

    def __init__(self,weight,age):
        self.weight = weight
        self.age = age

    def get_weight(self):
        return self.weight

    def get_age(self):
        return self.age

    def multiply(self):
        return self.weight*self.age


class foo_list(list):

    def __init__(self,foo_tuple):
        list.__init__(self,foo_tuple)

    def __getattribute__(self,name):
        return [getattr(x,name)() for x in self]

现在一个执行例子:

import fe

u=fe.foo_list((fe.foo(1,2),fe.foo(3,4)))
u.multiply
[2, 12]
u.multiply()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

但是这样方法属性就与结果相关联了。但我希望它成为一种调用方法,就像在包含的对象中一样

def __getattribute__(self,name):
    return [getattr(x,name)() for x in self]

__getattribute__ return是一个列表,也就是说u.multiply是一个列表;你然后试图打电话给它。如果你想让这个魔法属性伪装成一个方法,那么 __getattribute__ 将需要 return 一个可调用函数:

def __getattribute__(self, name):
    def f():
        return [getattr(x, name)() for x in self]
    return f