我试图创建一个子类,它充当自定义类的列表。但是,我希望列表继承父类的方法和属性,并返回每个项的数量之和。我正试图使用__getattribute__方法来实现这一点,但是我不知道如何将参数传递给可调用的属性。下面高度简化的代码应该解释得更清楚。class Product:
def __init__(self,price,quantity):
self.price=price
self.quantity=quantity
def get_total_price(self,tax_rate):
return self.price*self.quantity*(1+tax_rate)
class Package(Product,list):
def __init__(self,*args):
list.__init__(self,args)
def __getattribute__(self,*args):
name = args[0]
# the only argument passed is the name...
if name in dir(self[0]):
tot = 0
for product in self:
tot += getattr(product,name)#(need some way to pass the argument)
return sum
else:
list.__getattribute__(self,*args)
p1 = Product(2,4)
p2 = Product(1,6)
print p1.get_total_price(0.1) # returns 8.8
print p2.get_total_price(0.1) # returns 6.6
pkg = Package(p1,p2)
print pkg.get_total_price(0.1) #desired output is 15.4.
实际上,我有许多父类的方法必须是可调用的。我意识到我可以手动重写列表类子类的每个方法,但我希望避免这样做,因为将来可能会有更多的方法添加到父类中,我希望有一个动态系统。如有任何意见或建议,我们将不胜感激。谢谢!