我认为所谓“禁止”继承某个类Foo,实际上只是需要当有其他类继承Foo时发出警报,提醒未正常使用该类的其他人。Python没有final这样简单的语言机制让你禁止类继承,但我们可以通过许多其他方式来实现。例如,良好的沟通或文档就能有效的防止其他人继承你的类;当然也可以让类‘自己’报警,这里提供一种供参考:
# test.py
class Father(object):
def __new__(cls, *args, **kwargs):
if cls != Father:
raise Exception("You should not inherit from Father; Got subclass(es): " + str(Father.__subclasses__()))
return super(Father, cls).__new__(cls, *args, **kwargs)
def __init__(self, x):
self.x = x
class Son(Father):
def __init__(self, x):
self.x = x
现在,试着使用这两个类:
>>> from test import *
>>> Father(10)
>>> Son(10)
Traceback (most recent call last):
File "", line 1, in
File "test.py", line 4, in __new__
raise Exception("You should not inherit from Father; Got subclass(es): " + str(Father.__subclasses__()))
Exception: You should not inherit from Father; Got subclass(es): []
>>>
可以看到,Father类可以正常使用,但继承Father的Son类则不能正常使用。其原理是,当新建类实例时,python将首先调用其父类的__new__函数, 并以其自身的__class__为参数,所以在新建Father实例时,Father.__new__的cls参数值为Father; 而新建Son实例时, Son也将调用Father.__new__,但cls参数值为Son,这样就能够判断是否存在Father的子类。