類的定義
假如要定義一個(gè)類 Point,表示二維的坐標(biāo)點(diǎn):
# point.pyclass Point: def __init__(self, x=0, y=0): self.x, self.y = x, y
最最基本的就是 __init__ 方法,相當(dāng)于 C++ / Java 的構(gòu)造函數(shù)。帶雙下劃線 __ 的方法都是特殊方法,除了 __init__ 還有很多,后面會(huì)有介紹。
參數(shù) self 相當(dāng)于 C++ 的 this,表示當(dāng)前實(shí)例,所有方法都有這個(gè)參數(shù),但是調(diào)用時(shí)并不需要指定。
>>> 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)用)。
對(duì)一切皆對(duì)象的 Python 來說,類自己當(dāng)然也是對(duì)象:
>>> type(Point)<class 'type'>>>> dir(Point)['__class__', '__delattr__', '__dict__', ..., '__init__', ...]>>> Point.__class__<class 'type'>
Point 是 type 的一個(gè)實(shí)例,這和 p 是 Point 的一個(gè)實(shí)例是一回事。
現(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(...) 其實(shí)只是一個(gè)語法糖,你也可以寫成 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)成員),而不是對(duì)象的屬性了。
訪問控制
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 實(shí)例:
>>> p = Point(10, 10)>>> p<point.Point object at 0x000000000272AA20>
通常,這并不是我們想要的輸出,我們想要的是:
>>> pPoint(10, 10)
添加特殊方法 __repr__ 即可實(shí)現(xiàn):
class Point:  def __repr__(self):    return 'Point({}, {})'.format(self.__x, self.__y)            
新聞熱點(diǎn)
疑難解答
圖片精選