pythongetattribute方法怎么用_使用getattribute或getattr调用Python中的方法

我试图创建一个子类,它充当自定义类的列表。但是,我希望列表继承父类的方法和属性,并返回每个项的数量之和。我正试图使用__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.

实际上,我有许多父类的方法必须是可调用的。我意识到我可以手动重写列表类子类的每个方法,但我希望避免这样做,因为将来可能会有更多的方法添加到父类中,我希望有一个动态系统。如有任何意见或建议,我们将不胜感激。谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值