python的抽象类

抽象类:类中可以存在抽象方法,类中的抽象方法是由子类来实现,如果通过类的实例是不能被调用的抽象方法,只能由子类的实例对象来调用(子类要重写抽象方法)。

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
    def black_print(self,msg):
        print("这是戴尔的打印机",msg)

def say(printer:Print,msg):
    printer.black_print(msg)

if __name__ == '__main__':
    print1=DellPrinter()
    say(print1,'ss')      #应该抛出异常

基于abc模块进行实现


import abc


class Print:
    @abc.abstractmethod
    def black_print(self,msg):
        pass

    @abc.abstractmethod
    def rgb_print(self,msg):
        pass
    @abc.abstractstaticmethod
    def add_rgb():
        pass

    @abc.abstractclassmethod
    def add_paper(cls):
        pass
class DellPrinter(Print):
    def __init__(self):
        pass
    def black_print(self,msg):
        print("这是戴尔的打印机",msg)

    @staticmethod
    def add_rgb():
        print("这是颜色轨道")

    @classmethod
    def add_paper(cls):
        print("这是纸张")

def say(printer:Print,msg):
    printer.black_print(msg)

if __name__ == '__main__':
    print1=DellPrinter()
    say(print1,'ss')      #应该抛出异常

你可能感兴趣的:(python,抽象类,python)