1.1 導入模塊執(zhí)行class語句
python導入模塊時會執(zhí)行class語句及主體內(nèi)的頂層語句。
示例
# test.py
class MyClass:
print('MyClass')
# cmd執(zhí)行下面語句
E:\\documents\\F盤>python
>>> import test
MyClass
1.2 pytho類接口技術
python類接口技術通過繼承實現(xiàn)。
# test.py
class Super:
'''定義一個超類。
定義一個method方法。
定義一個delegate方法,方法內(nèi)調(diào)用子類定義的action方法。
'''
def method(self):
print('in Super.method')
def delegate(self):
'''調(diào)用子類定義的action'''
self.action()
class Inheritor(Super):pass
class Replacer(Super):
'''定義 Replacer 繼承 Super
替換超類的 method 方法
'''
def method(self):
print('in Replacer.method')
class Extender(Super):
'''定義 Extender 繼承 Super
調(diào)用超類的 method 方法, 并且進行擴展
'''
def method(self):
print('Begin Extender.method')
Super.method(self)
print('End Extender.method')
class Provider(Super):
'''定義 Provider 繼承 Super
實現(xiàn)超類 delegate 內(nèi)調(diào)用的 action 方法
'''
def action(self):
print('in Provider.action')
if __name__ == '__main__':
for cls in (Inheritor,Replacer,Extender,Provider):
print('\\n{}....'.format(cls.__name__))
cls().method()
print('\\nProvider')
p = Provider()
p.delegate()
''' 運行結果
E:\\documents\\F盤>python test.py
Inheritor....
in Super.method
Replacer....
in Replacer.method
Extender....
Begin Extender.method
in Super.method
End Extender.method
Provider....
in Super.method
Provider
in Provider.action
'''
1.3 python抽象超類
python類的部分行為由子類提供,則為抽象超類。
1.3.1 調(diào)用方法時觸發(fā)提示
顯式要求子類必須實現(xiàn)抽象超類的方法:
(1) 方法一,在超類方法用assert False
(2) 方法二,在超類方法用 raise NotImplementedError
未實現(xiàn),則在實例調(diào)用方法時觸發(fā)報錯提示。
子類和超類都未提供方法 ,報 has no attribute
>>> class AbsSuper:
def delegate(self):
self.action()
>>> class Provider(AbsSuper):pass
>>> p=Provider()
>>> p.delegate()
Traceback (most recent call last):
File ", line 1, in
在超類方法用assert False
>>> class AbsSuper:
def delegate(self):
self.action()
def action(self):
assert False,'子類必須定義 action'
>>> class Provider(AbsSuper):pass
>>> Provider().delegate()
Traceback (most recent call last):
File ", line 1, in
在超類方法用raise NotImplementedError
>>> class AbsSuper:
def delegate(self):
self.action()
def action(self):
raise NotImplementedError('子類必須定義 action')
>>> class Provider(AbsSuper):pass
>>> Provider().delegate()
Traceback (most recent call last):
File ", line 1, in
1.3.2 創(chuàng)建實例時觸發(fā)提示
(1) 帶有@abstractmethod修飾的方法為抽象方法。
(2) 帶有抽象方法的類不能進行實例化。
(3) 超類有抽象方法時,子類必須重寫超類的抽象方法。
(4) 未重寫,則創(chuàng)建實例時觸發(fā)報錯提示。
抽象方法定義:
(1) python3:超類頭部括號送metaclass**=**ABCMeta。
(2) python2:超類主體定義**metaclass****=**ABCMeta。
(3) 用@abstractmethod修飾方法。
python3示例
>>> from abc import ABCMeta,abstractmethod
>>> class MySuper(metaclass=ABCMeta):
def delegate(self):
self.action()
# @abstractmethod 為抽象方法,子類必須重寫
@abstractmethod
def action(self):
pass # 抽象方法在父類通常留空,用pass進行占位
>>> ms=MySuper()
Traceback (most recent call last):
File "
-
接口技術
+關注
關注
1文章
276瀏覽量
41430 -
Class
+關注
關注
0文章
53瀏覽量
19777 -
python
+關注
關注
56文章
4811瀏覽量
85077
發(fā)布評論請先 登錄
相關推薦
評論