假如要定義一個類 Point
,表示二維的座標點:python
# 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 來講,類本身固然也是對象:async
>>> type(Point) <class 'type'> >>> dir(Point) ['__class__', '__delattr__', '__dict__', ..., '__init__', ...] >>> Point.__class__ <class 'type'>
Point
是 type
的一個實例,這和 p
是 Point
的一個實例是一回事。ide
現添加方法 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
參數了:oop
>>> Point.set(p, 0, 0) >>> p.x, p.y (0, 0)
值得注意的是,self
並非關鍵字,甚至能夠用其它名字替代,好比 this
: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'
嘗試打印 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()
缺省使用 repr()
的結果。
這二者都是對象的字符串形式的表示,但仍是有點差異的。簡單來講,repr()
的結果面向的是解釋器,一般都是合法的 Python 代碼,好比 Point(10, 10)
;而 str()
的結果面向用戶,更簡潔,好比 (10, 10)
。
按照這個原則,咱們爲 Point
提供 __str__
的定義以下:
class Point: def __str__(self): return '({}, {})'.format(self.__x, self.__y)
兩個座標點相加是個很合理的需求。
>>> 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
這樣,它才更像一個接口。
有時候,須要在子類中調用父類的方法。
好比圖形都有顏色這個屬性,因此不妨加一個參數 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
是推薦的作法,由於它避免了硬編碼,也能處理多繼承的狀況。