Reputation: 5074
What is a best way to make a class that can't be initialized, but whose base classes can.
For example:
class A:
def __init__(self):
print('a')
class B(A):
pass
>>> B()
a
>>> A() # Raises an error.
The only way I can think of doing it right now is adding a test at the beginning of A.__init__
checking if self.__class__.__name__ == 'A':
, and raising an error if true but this isn't very flexible a solution. Is there any way of accomplishing this?
Upvotes: 2
Views: 213
Reputation: 799190
Check the type in the allocator:
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!'
Upvotes: 2