Skip to main content
 首页 » 编程设计

python之python中创建一个不可初始化但其子类可初始化的类的最佳方法

2024年10月25日8三少

创建无法初始化但其基类可以初始化的类的最佳方法是什么。

例如:

class A: 
    def __init__(self): 
        print('a') 
 
class B(A): 
    pass 
 
>>> B() 
a 
>>> A() # Raises an error. 

我现在能想到的唯一方法是在 A.__init__ 的开头添加一个测试,检查 if self.__class__.__name__ == 'A':,如果为真则引发错误,但这不是一个非常灵活的解决方案。有什么办法可以做到这一点吗?

请您参考如下方法:

检查分配器中的类型:

class Base(object): 
  def __new__(cls): 
    if cls is Base: 
      raise NotImplementedError() 
    super(Base, cls).__new__(cls) 
 
class Derived(Base): 
  pass 
 
try: 
  o = Base() 
except NotImplementedError: 
  print 'Should happen!' 
else: 
  print 'Should not happen!' 
 
try: 
  o = Derived() 
except NotImplementedError: 
  print 'Should not happen!' 
else: 
  print 'Should happen!'