日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
淺析Python的類、繼承和多態(tài)

類的定義

假如要定義一個類 Point,表示二維的坐標點:

 
 
 
 
  1. # point.py 
  2.  
  3. class Point: 
  4.  
  5.     def __init__(self, x=0, y=0): 
  6.  
  7.         self.x, self.y = x, y  

最最基本的就是 __init__ 方法,相當于 C++ / Java 的構造函數(shù)。帶雙下劃線 __ 的方法都是特殊方法,除了 __init__ 還有很多,后面會有介紹。

參數(shù) self 相當于 C++ 的 this,表示當前實例,所有方法都有這個參數(shù),但是調用時并不需要指定。

 
 
 
 
  1. >>> from point import * 
  2.  
  3. >>> p = Point(10, 10) # __init__ 被調用 
  4.  
  5. >>> type(p) 
  6.  
  7.  
  8.  
  9. >>> p.x, p.y 
  10.  
  11. (10, 10)  

幾乎所有的特殊方法(包括 __init__)都是隱式調用的(不直接調用)。

對一切皆對象的 Python 來說,類自己當然也是對象:

 
 
 
 
  1. >>> type(Point) 
  2.  
  3.  
  4.  
  5. >>> dir(Point) 
  6.  
  7. ['__class__', '__delattr__', '__dict__', ..., '__init__', ...] 
  8.  
  9. >>> Point.__class__ 
  10.  
  11.   

Point 是 type 的一個實例,這和 p 是 Point 的一個實例是一回事。

現(xiàn)添加方法 set:

 
 
 
 
  1. class Point: 
  2.  
  3.     ... 
  4.  
  5.     def set(self, x, y): 
  6.  
  7.         self.x, self.y = x, y  
 
 
 
 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p.set(0, 0) 
  4.  
  5. >>> p.x, p.y 
  6.  
  7. (0, 0)  

p.set(...) 其實只是一個語法糖,你也可以寫成 Point.set(p, ...),這樣就能明顯看出 p 就是 self 參數(shù)了:

 
 
 
 
  1. >>> Point.set(p, 0, 0) 
  2.  
  3. >>> p.x, p.y 
  4.  
  5. (0, 0)  

值得注意的是,self 并不是關鍵字,甚至可以用其它名字替代,比如 this:

 
 
 
 
  1. class Point: 
  2.  
  3. ... 
  4.  
  5. def set(this, x, y): 
  6.  
  7. this.x, this.y = x, y  

與 C++ 不同的是,“成員變量”必須要加 self. 前綴,否則就變成類的屬性(相當于 C++ 靜態(tài)成員),而不是對象的屬性了。

訪問控制

Python 沒有 public / protected / private 這樣的訪問控制,如果你非要表示“私有”,習慣是加雙下劃線前綴。

 
 
 
 
  1. class Point: 
  2.  
  3.     def __init__(self, x=0, y=0): 
  4.  
  5.         self.__x, self.__y = x, y 
  6.  
  7.   
  8.  
  9.     def set(self, x, y): 
  10.  
  11.         self.__x, self.__y = x, y 
  12.  
  13.   
  14.  
  15.     def __f(self): 
  16.  
  17.         pass  

__x、__y 和 __f 就相當于私有了:

 
 
 
 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p.__x 
  4.  
  5. ... 
  6.  
  7. AttributeError: 'Point' object has no attribute '__x' 
  8.  
  9. >>> p.__f() 
  10.  
  11. ... 
  12.  
  13. AttributeError: 'Point' object has no attribute '__f'  

_repr_

嘗試打印 Point 實例:

 
 
 
 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p 
  4.  
  5.   

通常,這并不是我們想要的輸出,我們想要的是:

 
 
 
 
  1. >>> p 
  2.  
  3. Point(10, 10)  

添加特殊方法 __repr__ 即可實現(xiàn):

 
 
 
 
  1. class Point: 
  2.  
  3. def __repr__(self): 
  4.  
  5. return 'Point({}, {})'.format(self.__x, self.__y)  

不難看出,交互模式在打印 p 時其實是調用了 repr(p):

 
 
 
 
  1. >>> repr(p) 
  2.  
  3. 'Point(10, 10)'  

_str_

如果沒有提供 __str__,str() 缺省使用 repr() 的結果。

這兩者都是對象的字符串形式的表示,但還是有點差別的。簡單來說,repr() 的結果面向的是解釋器,通常都是合法的 Python 代碼,比如 Point(10, 10);而 str() 的結果面向用戶,更簡潔,比如 (10, 10)。

按照這個原則,我們?yōu)?Point 提供 __str__ 的定義如下:

 
 
 
 
  1. class Point: 
  2.  
  3. def __str__(self): 
  4.  
  5. return '({}, {})'.format(self.__x, self.__y)  

_add_

兩個坐標點相加是個很合理的需求。

 
 
 
 
  1. >>> p1 = Point(10, 10) 
  2.  
  3. >>> p2 = Point(10, 10) 
  4.  
  5. >>> p3 = p1 + p2 
  6.  
  7. Traceback (most recent call last): 
  8.  
  9. File "", line 1, in  
  10.  
  11. TypeError: unsupported operand type(s) for +: 'Point' and 'Point'  

添加特殊方法 __add__ 即可做到:

 
 
 
 
  1. class Point: 
  2.  
  3. def __add__(self, other): 
  4.  
  5. return Point(self.__x + other.__x, self.__y + other.__y)  
 
 
 
 
  1. >>> p3 = p1 + p2 
  2.  
  3. >>> p3 
  4.  
  5. Point(20, 20)  

這就像 C++ 里的操作符重載一樣。

Python 的內建類型,比如字符串、列表,都“重載”了 + 操作符。

特殊方法還有很多,這里就不逐一介紹了。

繼承

舉一個教科書中最常見的例子。Circle 和 Rectangle 繼承自 Shape,不同的圖形,面積(area)計算方式不同。

 
 
 
 
  1. # shape.py 
  2.  
  3.   
  4.  
  5. class Shape: 
  6.  
  7.     def area(self): 
  8.  
  9.         return 0.0 
  10.  
  11.          
  12.  
  13. class Circle(Shape): 
  14.  
  15.     def __init__(self, r=0.0): 
  16.  
  17.         self.r = r 
  18.  
  19.   
  20.  
  21.     def area(self): 
  22.  
  23.         return math.pi * self.r * self.r 
  24.  
  25.   
  26.  
  27. class Rectangle(Shape): 
  28.  
  29.     def __init__(self, a, b): 
  30.  
  31.         self.a, self.b = a, b 
  32.  
  33.   
  34.  
  35.     def area(self): 
  36.  
  37.         return self.a * self.b  

用法比較直接:

 
 
 
 
  1. >>> from shape import * 
  2.  
  3. >>> circle = Circle(3.0) 
  4.  
  5. >>> circle.area() 
  6.  
  7. 28.274333882308138 
  8.  
  9. >>> rectangle = Rectangle(2.0, 3.0) 
  10.  
  11. >>> rectangle.area() 
  12.  
  13. 6.0  

如果 Circle 沒有定義自己的 area:

 
 
 
 
  1. class Circle(Shape): 
  2.  
  3. pass  

那么它將繼承父類 Shape 的 area:

 
 
 
 
  1. >>> Shape.area is Circle.area 
  2.  
  3. True  

一旦 Circle 定義了自己的 area,從 Shape 繼承而來的那個 area 就被重寫(overwrite)了:

 
 
 
 
  1. >>> from shape import * 
  2.  
  3. >>> Shape.area is Circle.area 
  4.  
  5. False  

通過類的字典更能明顯地看清這一點:

 
 
 
 
  1. >>> Shape.__dict__['area'] 
  2.  
  3.  
  4.  
  5. >>> Circle.__dict__['area'] 
  6.  
  7.   

所以,子類重寫父類的方法,其實只是把相同的屬性名綁定到了不同的函數(shù)對象。可見 Python 是沒有覆寫(override)的概念的。

同理,即使 Shape 沒有定義 area 也是可以的,Shape 作為“接口”,并不能得到語法的保證。

甚至可以動態(tài)的添加方法:

 
 
 
 
  1. class Circle(Shape): 
  2.  
  3. ... 
  4.  
  5. # def area(self): 
  6.  
  7. # return math.pi * self.r * self.r 
  8.  
  9. # 為 Circle 添加 area 方法。 
  10.  
  11. Circle.area = lambda self: math.pi * self.r * self.r  

動態(tài)語言一般都是這么靈活,Python 也不例外。

Python 官方教程「9. Classes」***句就是:

Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics.

Python 以最少的新的語法和語義實現(xiàn)了類機制,這一點確實讓人驚嘆,但是也讓 C++ / Java 程序員感到頗為不適。

多態(tài)

如前所述,Python 沒有覆寫(override)的概念。嚴格來講,Python 并不支持「多態(tài)」。

為了解決繼承結構中接口和實現(xiàn)的問題,或者說為了更好的用 Python 面向接口編程(設計模式所提倡的),我們需要人為的設一些規(guī)范。

請考慮 Shape.area() 除了簡單的返回 0.0,有沒有更好的實現(xiàn)?

以內建模塊 asyncio 為例,AbstractEventLoop 原則上是一個接口,類似于 Java 中的接口或 C++ 中的純虛類,但是 Python 并沒有語法去保證這一點,為了盡量體現(xiàn) AbstractEventLoop 是一個接口,首先在名字上標志它是抽象的(Abstract),然后讓每個方法都拋出異常 NotImplementedError。

 
 
 
 
  1. class AbstractEventLoop: 
  2.  
  3. def run_forever(self): 
  4.  
  5. raise NotImplementedError 
  6.  
  7. ...  

縱然如此,你是無法禁止用戶實例化 AbstractEventLoop 的:

 
 
 
 
  1. loop = asyncio.AbstractEventLoop() 
  2.  
  3. try: 
  4.  
  5. loop.run_forever() 
  6.  
  7. except NotImplementedError: 
  8.  
  9. pass  

C++ 可以通過純虛函數(shù)或設構造函數(shù)為 protected 來避免接口被實例化,Java 就更不用說了,接口就是接口,有完整的語法支持。

你也無法強制子類必須實現(xiàn)“接口”中定義的每一個方法,C++ 的純虛函數(shù)可以強制這一點(Java 更不必說)。

就算子類「自以為」實現(xiàn)了“接口”中的方法,也不能保證方法的名字沒有寫錯,C++ 的 override 關鍵字可以保證這一點(Java 更不必說)。

靜態(tài)類型的缺失,讓 Python 很難實現(xiàn) C++ / Java 那樣嚴格的多態(tài)檢查機制。所以面向接口的編程,對 Python 來說,更多的要依靠程序員的素養(yǎng)。

回到 Shape 的例子,仿照 asyncio,我們把“接口”改成這樣:

 
 
 
 
  1. class AbstractShape: 
  2.  
  3. def area(self): 
  4.  
  5. raise NotImplementedError  

這樣,它才更像一個接口。

super

有時候,需要在子類中調用父類的方法。

比如圖形都有顏色這個屬性,所以不妨加一個參數(shù) color 到 __init__:

 
 
 
 
  1. class AbstractShape: 
  2.  
  3. def __init__(self, color): 
  4.  
  5. self.color = color  

那么子類的 __init__() 勢必也要跟著改動:

 
 
 
 
  1. class Circle(AbstractShape): 
  2.  
  3. def __init__(self, color, r=0.0): 
  4.  
  5. super().__init__(color) 
  6.  
  7. self.r = r  

通過 super 把 color 傳給父類的 __init__()。其實不用 super 也行:

 
 
 
 
  1. class Circle(AbstractShape): 
  2.  
  3. def __init__(self, color, r=0.0): 
  4.  
  5. AbstractShape.__init__(self, color) 
  6.  
  7. self.r = r  

但是 super 是推薦的做法,因為它避免了硬編碼,也能處理多繼承的情況。


網(wǎng)站標題:淺析Python的類、繼承和多態(tài)
網(wǎng)頁URL:http://www.dlmjj.cn/article/dphjiho.html