调用未绑定的父类方法和使用supper 函数 之间的选择.
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                调用未绑定的父类方法和使用supper 函数 之间的选择.
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                            class New_int(int):   # 定義一個新的類  繼承 int 類def __add__(self,other):   # 重寫 + 運算符 # __add__ 就是 int 中 +  的行為return int.__sub__(self,other)    # 重寫的 加法運算符 調用 int類 里面的 減法運算運算符def __sub__(self,other):return int.__add__(self,other)# 上面的是一個小小的惡作劇 . 把加法和減法的名稱進行了互換.   1 >>> a=New_int(5)
2 >>> b=New_int(3)
3 >>> a+b
4 2  
                        
                        
                        ?
上面的是調用未綁定的父類方法.
下面是使用super函數
class New_int(int): # 定義一個新的類 繼承 int 類def __add__(self,other): # 重寫 + 運算符 # __add__ 就是 int 中 + 的行為return super.__sub__(self,other) # 重寫的 加法運算符 調用 int類 里面的 減法運算運算符def __sub__(self,other):return super.__add__(self,other)# 上面的是一個小小的惡作劇 . 把加法和減法的名稱進行了互換. =============== RESTART: C:/Users/Administrator/Desktop/new.py =============== >>> a=New_int(5) >>> b=New_int(3) >>> a+b Traceback (most recent call last):File "<pyshell#12>", line 1, in <module>a+bFile "C:/Users/Administrator/Desktop/new.py", line 3, in __add__return super.__sub__(self,other) # 重寫的 加法運算符 調用 int類 里面的 減法運算運算符 AttributeError: type object 'super' has no attribute '__sub__'可見當使用super的時候 報錯提示 super中沒有__sub__ ? .......然而我不知道為什么會這樣 . 網上沒找到相關資料 . 等學的多了 ,再來看看 .
?
1 class int(int): 2 def __add__(self,other): 3 return int.__sub__(self,other) 4 5 '''def __sub__(self,other): 6 return int.__add__(self,other)''' 7 # 上面的 兩個重寫只能在同一時間內重寫一個 , 不然的話 , 就會報錯..... 8 # 當寫第二個的 add 的時候 系統不知道 會認為是 你重寫的 add 然后程序就崩潰了.?
轉載于:https://www.cnblogs.com/A-FM/p/5677325.html
總結
以上是生活随笔為你收集整理的调用未绑定的父类方法和使用supper 函数 之间的选择.的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: PHP流式上传和表单上传(美图秀秀)
 - 下一篇: 梦到杀人代表什么