小编AJ *_*ord的帖子

使用__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. …
Run Code Online (Sandbox Code Playgroud)

python getattr getattribute

10
推荐指数
2
解决办法
9164
查看次数

标签 统计

getattr ×1

getattribute ×1

python ×1