python如何定义抽象类_是否可以在Python中创建抽象类?

这里有一个非常简单的方法,不用处理ABC模块。

在要成为抽象类的类的__init__方法中,可以检查self的“type”。如果self的类型是基类,则调用方试图实例化基类,因此引发异常。下面是一个简单的例子:class Base():

def __init__(self):

if type(self) is Base:

raise Exception('Base is an abstract class and cannot be instantiated directly')

# Any initialization code

print('In the __init__ method of the Base class')

class Sub(Base):

def __init__(self):

print('In the __init__ method of the Sub class before calling __init__ of the Base class')

super().__init__()

print('In the __init__ method of the Sub class after calling __init__ of the Base class')

subObj = Sub()

baseObj = Base()

运行时,它会产生:In the `__init__` method of the Sub class before calling `__init__` of the Base class

In the `__init__` method of the Base class

In the `__init__` method of the Sub class after calling `__init__` of the Base class

Traceback (most recent call last):

File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 16, in

baseObj = Base()

File "/Users/irvkalb/Desktop/Demo files/Abstract.py", line 4, in `__init__`

raise Exception('Base is an abstract class and cannot be instantiated directly')

Exception: Base is an abstract class and cannot be instantiated directly

这表明可以实例化从基类继承的子类,但不能直接实例化基类。

内部收益率

你可能感兴趣的:(python如何定义抽象类)