2017-10-16 66 views
1

我的代码:控制台在交互模式下覆盖方法?

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 

或者尝试拉姆达:

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

在控制台中,对象的属性可以很容易地overwrited, 如何o改写它的方法?

+0

您需要修正的方法添加到类('Product'),而不是实例( 'book')。 – jasonharper

+0

它可以在控制台中的script_mode.errors报告中进行修改,Product.get_discount_amount = get_discount_amount_correct',In [26]:Product.get_discount_amount Out [26]: '@jasonharper –

回答

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