python的抽象類

2021-10-06 20:43:20 字數 2046 閱讀 9614

抽象類:類中可以存在抽象方法,類中的抽象方法是由子類來實現,如果通過類的例項是不能被呼叫的抽象方法,只能由子類的例項物件來呼叫(子類要重寫抽象方法)。

class

print

:def

black_print

(msg)

:raise exception(

'必須子類實現'

)def

rgb_print

(msg)

:pass

print

=print(

)print

.black_print(

'sss'

)#應該丟擲異常

寫子類來重寫父類方法

class

print

:def

__init__

(self)

:raise exception(

"此類是介面類"

)def

black_print

(self,msg)

:raise exception(

'必須子類實現'

)def

rgb_print

(self,msg)

:raise exception(

'必須子類實現'

)class

dellprinter

(print)

:def

__init__

(self)

:pass

defblack_print

(self,msg)

:print

("這是戴爾的印表機"

,msg)

defsay

(printer:print,msg)

: printer.black_print(msg)

if __name__ ==

'__main__'

: print1=dellprinter(

) say(print1,

'ss'

)#應該丟擲異常

基於abc模組進行實現

import abc

class

print

: @abc.abstractmethod

defblack_print

(self,msg)

:pass

@abc.abstractmethod

defrgb_print

(self,msg)

:pass

@abc.abstractstaticmethod

defadd_rgb()

:pass

@abc.abstractclassmethod

defadd_*****

(cls)

:pass

class

dellprinter

(print)

:def

__init__

(self)

:pass

defblack_print

(self,msg)

:print

("這是戴爾的印表機"

,msg)

@staticmethod

defadd_rgb()

:print

("這是顏色軌道"

) @classmethod

defadd_*****

(cls)

:print

("這是紙張"

)def

say(printer:print,msg)

: printer.black_print(msg)

if __name__ ==

'__main__'

: print1=dellprinter(

) say(print1,

'ss'

)#應該丟擲異常

python的抽象類

可以借助庫abc來實現 先建立類a import abc class a metaclass abc.abcmeta 抽象類 abc.abstractmethod 宣告抽象方法 defread self pass abc.abstractmethod defwrite self pass def s...

Python 介面類 抽象類

建立乙個介面類 抽象類的規範 from abc import abstractmethod,abcmeta class payment metaclass abcmeta 元類 預設的元類 type abstractmethod def pay self,money pass 沒有實現這個方法 介面...

python抽象類 抽象方法的實現

由於python沒有抽象類 介面的概念,所以要實現這種功能得abc.py這個類庫,具體方式如下 coding utf 8 import abc 抽象類 class studentbase object metaclass abc.abcmeta abc.abstractmethod defstudy...