2017-10-16 73 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