淺析Python的類、繼承和多態

esky 8年前發布 | 22K 次閱讀 Python Python開發

類的定義

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

# point.py 
 
class Point: 
 
    def __init__(self, x=0, y=0): 
 
        self.x, self.y = x, y  

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

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

>>> from point import * 
 
>>> p = Point(10, 10) # __init__ 被調用 
 
>>> type(p) 
 
<class 'point.Point'> 
 
>>> p.x, p.y 
 
(10, 10)  

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

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

>>> type(Point) 
 
<class 'type'> 
 
>>> dir(Point) 
 
['__class__', '__delattr__', '__dict__', ..., '__init__', ...] 
 
>>> Point.__class__ 
 
<class 'type'>  

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

現添加方法 set:

class Point: 
 
    ... 
 
    def set(self, x, y): 
 
        self.x, self.y = x, y  
>>> p = Point(10, 10) 
 
>>> p.set(0, 0) 
 
>>> p.x, p.y 
 
(0, 0)  

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

>>> Point.set(p, 0, 0) 
 
>>> p.x, p.y 
 
(0, 0)  

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

class Point: 
 
... 
 
def set(this, x, y): 
 
this.x, this.y = x, y  

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

訪問控制

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

class Point: 
 
    def __init__(self, x=0, y=0): 
 
        self.__x, self.__y = x, y 
 
  
 
    def set(self, x, y): 
 
        self.__x, self.__y = x, y 
 
  
 
    def __f(self): 
 
        pass  

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

>>> p = Point(10, 10) 
 
>>> p.__x 
 
... 
 
AttributeError: 'Point' object has no attribute '__x' 
 
>>> p.__f() 
 
... 
 
AttributeError: 'Point' object has no attribute '__f'  

_repr_

嘗試打印 Point 實例:

>>> p = Point(10, 10) 
 
>>> p 
 
<point.Point object at 0x000000000272AA20>  

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

>>> p 
 
Point(10, 10)  

添加特殊方法 __repr__ 即可實現:

class Point: 
 
def __repr__(self): 
 
return 'Point({}, {})'.format(self.__x, self.__y)  

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

>>> repr(p) 
 
'Point(10, 10)'  

_str_

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

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

按照這個原則,我們為 Point 提供 __str__ 的定義如下:

class Point: 
 
def __str__(self): 
 
return '({}, {})'.format(self.__x, self.__y)  

_add_

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

>>> p1 = Point(10, 10) 
 
>>> p2 = Point(10, 10) 
 
>>> p3 = p1 + p2 
 
Traceback (most recent call last): 
 
File "<stdin>", line 1, in <module> 
 
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'  

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

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

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

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

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

繼承

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

# shape.py 
 
  
 
class Shape: 
 
    def area(self): 
 
        return 0.0 
 
         
 
class Circle(Shape): 
 
    def __init__(self, r=0.0): 
 
        self.r = r 
 
  
 
    def area(self): 
 
        return math.pi * self.r * self.r 
 
  
 
class Rectangle(Shape): 
 
    def __init__(self, a, b): 
 
        self.a, self.b = a, b 
 
  
 
    def area(self): 
 
        return self.a * self.b  

用法比較直接:

>>> from shape import * 
 
>>> circle = Circle(3.0) 
 
>>> circle.area() 
 
28.274333882308138 
 
>>> rectangle = Rectangle(2.0, 3.0) 
 
>>> rectangle.area() 
 
6.0  

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

class Circle(Shape): 
 
pass  

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

>>> Shape.area is Circle.area 
 
True  

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

>>> from shape import * 
 
>>> Shape.area is Circle.area 
 
False  

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

>>> Shape.__dict__['area'] 
 
<function Shape.area at 0x0000000001FDB9D8> 
 
>>> Circle.__dict__['area'] 
 
<function Circle.area at 0x0000000001FDBB70>  

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

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

甚至可以動態的添加方法:

class Circle(Shape): 
 
... 
 
# def area(self): 
 
# return math.pi * self.r * self.r 
 
# 為 Circle 添加 area 方法。 
 
Circle.area = lambda self: math.pi * self.r * self.r  

動態語言一般都是這么靈活,Python 也不例外。

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

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

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

多態

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

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

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

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

class AbstractEventLoop: 
 
def run_forever(self): 
 
raise NotImplementedError 
 
...  

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

loop = asyncio.AbstractEventLoop() 
 
try: 
 
loop.run_forever() 
 
except NotImplementedError: 
 
pass  

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

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

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

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

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

class AbstractShape: 
 
def area(self): 
 
raise NotImplementedError  

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

super

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

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

class AbstractShape: 
 
def __init__(self, color): 
 
self.color = color  

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

class Circle(AbstractShape): 
 
def __init__(self, color, r=0.0): 
 
super().__init__(color) 
 
self.r = r  

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

class Circle(AbstractShape): 
 
def __init__(self, color, r=0.0): 
 
AbstractShape.__init__(self, color) 
 
self.r = r  

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

 

來自:http://developer.51cto.com/art/201707/545393.htm

 

 本文由用戶 esky 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!