Python 的類、繼承和多態(tài)詳解
類的定義
假如要定義一個類 Point,表示二維的坐標(biāo)點:
# point.py class Point: def __init__(self, x=0, y=0): self.x, self.y = x, y
最最基本的就是 __init__ 方法,相當(dāng)于 C++ / Java 的構(gòu)造函數(shù)。帶雙下劃線 __ 的方法都是特殊方法,除了 __init__ 還有很多,后面會有介紹。
參數(shù) self 相當(dāng)于 C++ 的 this,表示當(dāng)前實例,所有方法都有這個參數(shù),但是調(diào)用時并不需要指定。
>>> from point import * >>> p = Point(10, 10) # __init__ 被調(diào)用 >>> type(p) <class 'point.Point'> >>> p.x, p.y (10, 10)
幾乎所有的特殊方法(包括 __init__)都是隱式調(diào)用的(不直接調(diào)用)。
對一切皆對象的 Python 來說,類自己當(dāng)然也是對象:
>>> type(Point) <class 'type'> >>> dir(Point) ['__class__', '__delattr__', '__dict__', ..., '__init__', ...] >>> Point.__class__ <class 'type'>
Point 是 type 的一個實例,這和 p 是 Point 的一個實例是一回事。
現(xiàn)添加方法 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 參數(shù)了:
>>> Point.set(p, 0, 0) >>> p.x, p.y (0, 0)
值得注意的是,self 并不是關(guān)鍵字,甚至可以用其它名字替代,比如 this:
class Point: ... def set(this, x, y): this.x, this.y = x, y
與 C++ 不同的是,“成員變量”必須要加 self. 前綴,否則就變成類的屬性(相當(dāng)于 C++ 靜態(tài)成員),而不是對象的屬性了。
訪問控制
Python 沒有 public / protected / private 這樣的訪問控制,如果你非要表示“私有”,習(xí)慣是加雙下劃線前綴。
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 就相當(dāng)于私有了:
>>> 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__ 即可實現(xiàn):
class Point: def __repr__(self): return 'Point({}, {})'.format(self.__x, self.__y)
不難看出,交互模式在打印 p 時其實是調(diào)用了 repr(p):
>>> repr(p)
'Point(10, 10)'
_str_
如果沒有提供 __str__,str() 缺省使用 repr() 的結(jié)果。
這兩者都是對象的字符串形式的表示,但還是有點差別的。簡單來說,repr() 的結(jié)果面向的是解釋器,通常都是合法的 Python 代碼,比如 Point(10, 10);而 str() 的結(jié)果面向用戶,更簡潔,比如 (10, 10)。
按照這個原則,我們?yōu)?Point 提供 __str__ 的定義如下:
class Point: def __str__(self): return '({}, {})'.format(self.__x, self.__y)
_add_
兩個坐標(biāo)點相加是個很合理的需求。
>>> 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 的內(nèi)建類型,比如字符串、列表,都“重載”了 + 操作符。
特殊方法還有很多,這里就不逐一介紹了。
繼承
舉一個教科書中最常見的例子。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>
所以,子類重寫父類的方法,其實只是把相同的屬性名綁定到了不同的函數(shù)對象??梢?Python 是沒有覆寫(override)的概念的。
同理,即使 Shape 沒有定義 area 也是可以的,Shape 作為“接口”,并不能得到語法的保證。
甚至可以動態(tài)的添加方法:
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
動態(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)的概念。嚴(yán)格來講,Python 并不支持「多態(tài)」。
為了解決繼承結(jié)構(gòu)中接口和實現(xiàn)的問題,或者說為了更好的用 Python 面向接口編程(設(shè)計模式所提倡的),我們需要人為的設(shè)一些規(guī)范。
請考慮 Shape.area() 除了簡單的返回 0.0,有沒有更好的實現(xiàn)?
以內(nèi)建模塊 asyncio 為例,AbstractEventLoop 原則上是一個接口,類似于 Java 中的接口或 C++ 中的純虛類,但是 Python 并沒有語法去保證這一點,為了盡量體現(xiàn) AbstractEventLoop 是一個接口,首先在名字上標(biāo)志它是抽象的(Abstract),然后讓每個方法都拋出異常 NotImplementedError。
class AbstractEventLoop: def run_forever(self): raise NotImplementedError ...
縱然如此,你是無法禁止用戶實例化 AbstractEventLoop 的:
loop = asyncio.AbstractEventLoop() try: loop.run_forever() except NotImplementedError: pass
C++ 可以通過純虛函數(shù)或設(shè)構(gòu)造函數(shù)為 protected 來避免接口被實例化,Java 就更不用說了,接口就是接口,有完整的語法支持。
你也無法強制子類必須實現(xiàn)“接口”中定義的每一個方法,C++ 的純虛函數(shù)可以強制這一點(Java 更不必說)。
就算子類「自以為」實現(xiàn)了“接口”中的方法,也不能保證方法的名字沒有寫錯,C++ 的 override 關(guān)鍵字可以保證這一點(Java 更不必說)。
靜態(tài)類型的缺失,讓 Python 很難實現(xiàn) C++ / Java 那樣嚴(yán)格的多態(tài)檢查機制。所以面向接口的編程,對 Python 來說,更多的要依靠程序員的素養(yǎng)。
回到 Shape 的例子,仿照 asyncio,我們把“接口”改成這樣:
class AbstractShape: def area(self): raise NotImplementedError
這樣,它才更像一個接口。
super
有時候,需要在子類中調(diào)用父類的方法。
比如圖形都有顏色這個屬性,所以不妨加一個參數(shù) 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 是推薦的做法,因為它避免了硬編碼,也能處理多繼承的情況。
相關(guān)文章
python回溯算法實現(xiàn)全排列小練習(xí)分享
這篇文章主要給大家分享的是python回溯算法實現(xiàn)全排列小練習(xí),文章根據(jù)例子:輸入列表L(不含重復(fù)元素),輸出L的全排列展開學(xué)習(xí),需要的小伙伴可以參考一下2022-02-02python如何利用matplotlib繪制并列雙柱狀圖并標(biāo)注數(shù)值
Python之中最好的圖表庫叫matplotlib,matplotlib,顧名思義就是提供了一整套和matlab相似的API,它的文檔相當(dāng)完備,下面這篇文章主要給大家介紹了關(guān)于python如何利用matplotlib繪制并列雙柱狀圖并標(biāo)注數(shù)值的相關(guān)資料,需要的朋友可以參考下2022-04-04Python實現(xiàn)識別圖片內(nèi)容的方法分析
這篇文章主要介紹了Python實現(xiàn)識別圖片內(nèi)容的方法,結(jié)合實例形式分析了tesseract模塊的下載、安裝配置及使用tesseract模塊進行圖片識別的相關(guān)操作技巧,需要的朋友可以參考下2018-07-07