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 <module>
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
这里有一个非常简单的方法,不用处理ABC模块。
在要成为抽象类的类的
__init__
方法中,可以检查self的“type”。如果self的类型是基类,则调用方试图实例化基类,因此引发异常。下面是一个简单的例子:运行时,它会产生:
这表明可以实例化从基类继承的子类,但不能直接实例化基类。
内部收益率
使用^{} 模块创建抽象类。使用^{} 装饰器声明方法抽象,并使用三种方法之一声明类抽象,具体取决于Python版本。
在Python 3.4及更高版本中,可以从^{} 继承。在早期版本的Python中,需要将类的元类指定为^{} 。在Python 3和Python 2中,指定元类有不同的语法。三种可能性如下所示:
无论使用哪种方法,都无法实例化具有抽象方法的抽象类,但可以实例化提供这些方法的具体定义的子类:
以前的方法(pre-PEP 3119)就是在调用抽象方法时在抽象类中
raise NotImplementedError
。这不像使用
abc
模块那样具有良好的属性。您仍然可以实例化抽象基类本身,在运行时调用抽象方法之前,您不会发现错误。但是,如果您处理的是一小组简单类,可能只是几个抽象方法,那么这种方法比试图遍历
abc
文档要简单一些。相关问题 更多 >
编程相关推荐