python中创建不可初始化但其子类可初始化的类的最佳方法
创建不能初始化但基类可以初始化的类的最佳方法是什么 例如:python中创建不可初始化但其子类可初始化的类的最佳方法,python,class,oop,class-hierarchy,Python,Class,Oop,Class Hierarchy,创建不能初始化但基类可以初始化的类的最佳方法是什么 例如: class A: def __init__(self): print('a') class B(A): pass >>> B() a >>> A() # Raises an error. 我现在唯一能想到的方法是在a的开头添加一个测试。如果self.\uuu init.\uuuuuuuuu检查if self.\uuuu class.\uuuuuu name.\uu
class A:
def __init__(self):
print('a')
class B(A):
pass
>>> B()
a
>>> A() # Raises an error.
我现在唯一能想到的方法是在
a的开头添加一个测试。如果self.\uuu init.\uuuuuuuuu
检查if self.\uuuu class.\uuuuuu name.\uuuuuuuu=='a':
,如果为true,则会引发一个错误,但这不是一个非常灵活的解决方案。有没有办法做到这一点?检查分配器中的类型:
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!'
好吧,我想我们可以让一个元类对任何类都能更普遍地做到这一点?@user3002473是的,通过在类上提供
\uuuuuuuuuuuu
属性绝对可以。