user3002473
user3002473

Reputation: 5074

Best way in python to make a class that is uninitializable but whose child classes are initializable

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

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions