在交互模式的控制台中覆盖方法?

时间:2017-10-16 13:04:10

标签: python-3.x

我有代码:

class Product:
    def __init__(self,name, price,discount):
        self.name = name
        self.price = price
        self.discount = discount

    def get_discount_amout(self):
        return self.price * self.discount

我将代码复制到IPython控制台并创建一个实例:

In [2]: book = Product('Think Python', 12.99, 30)

计算折扣金额

In [5]: book.get_discount_amout()
Out[5]: 389.7

我发现拼写错误和算术错误,立即在控制台中纠正它们。 首先,我定义了一个正确的get_discount_amount函数。

def get_discount_amount_correct(self):
    return self.price * self.discount/100

第二个覆盖book之前的方法。

book.get_discount_amount = get_discount_amount_correct

测试它。

In [13]: book.get_discount_amount
Out[13]: <function __main__.get_discount_amount_correct>

...意想不到然后

In [14]: book.get_discount_amount()
TypeError: get_discount_amount_correct() missing 1 required positional argument: 'self'

试,

In [15]: book.get_discount_amount(self)
NameError: name 'self' is not defined

或者尝试lambda:

In [16]: book.get_discount_amount = lambda self: self.price * self.discount/100
TypeError: <lambda>() missing 1 required positional argument: 'self'

在控制台中,对象的属性很容易被淹没, 如何覆盖其方法?

1 个答案:

答案 0 :(得分:2)

选项1

继续替换实例的方法,而不是类型,并将book作为self传递:

book.get_discount_amount(book)

选项2

替换类型的方法:

Product.get_discount_amount = get_discount_amount_correct

然后您创建的每个新Product都将使用替​​换的方法:

new_book = Product('New book', 20, 10)
new_book.get_discount_amount() # prints 2