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改寫它的方法?
您需要修正的方法添加到類('Product'),而不是實例( 'book')。 – jasonharper
它可以在控制檯中的script_mode.errors報告中進行修改,Product.get_discount_amount = get_discount_amount_correct',In [26]:Product.get_discount_amount Out [26]: '@jasonharper –