I have a list containing objects of same class. now I want to make that list a container class that relates to all methods of the objects it contains as you can see in my example below. But since I have a lot of methods, I don't want to explicitly write them down in the containing container-class like this again:
module 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]
Now an execution example:
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
But this way the method-attribute got related to the result. but I want it to be a method to call just like in the contained objects
CodePudding user response:
def __getattribute__(self,name):
return [getattr(x,name)() for x in self]
__getattribute__
returns a list, which means just u.multiply
is a list; which you're then trying to call. If you want this magic attribute to pose as a method, then __getattribute__
will need to return a callable function:
def __getattribute__(self, name):
def f():
return [getattr(x, name)() for x in self]
return f