カスタム クラスのリストとして機能するサブクラスを作成しようとしています。ただし、リストが親クラスのメソッドと属性を継承し、各アイテムの数量の合計を返すようにしたいと考えています。メソッドを使用してこれを実行しようとしています__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.
実際には、呼び出し可能でなければならない親クラスのメソッドがたくさんあります。リストのようなサブクラスのそれぞれを手動でオーバーライドできることはわかっていますが、将来、親クラスにさらにメソッドが追加される可能性があり、動的システムが必要なため、それは避けたいと思います。アドバイスや提案をいただければ幸いです。ありがとう!