我正在寻找类似的东西:
from abc import ABC
@abstractclass
class A(ABC):
pass
A() # FAILS
class B(A):
pass
B() # SUCCEEDS
我知道可以选择使用A
在abstractmethod
中修饰c或者某个虚拟方法,但这需要我在B
中覆盖它。这正是我试图避免的。
答案 0 :(得分:1)
您可以自定义__new__
:
from abc import ABC, abstractmethod
class A(ABC):
def __new__(cls):
if cls is A:
raise TypeError("Can't instantiate abstract class {}".format(A.__name__))
return super(A, cls).__new__(cls)
class B(A):
pass
A() # TypeError
B() # Ok
你也可以使它成为装饰风格,例如像这样(只要装饰的类没有自定义__new__
就可以工作):
def abstractclass(decorated_cls):
def clsnew(cls):
if cls is decorated_cls:
raise TypeError("Can't instantiate abstract class {}".format(decorated_cls.__name__))
return super(decorated_cls, cls).__new__(cls)
decorated_cls.__new__ = clsnew
return decorated_cls
@abstractclass
class A(ABC):
pass
class B(A):
pass
A() # TypeError
B() # Ok