Jimmy C
Jimmy C

Reputation: 9680

Raise error if initiating a class, but not when initiating its subclasses

I'm implementing what I guess would be similar to an abstract class in Python. Here's an example:

In [12]: class A(object):
   ....:     def __init__(self, b):
   ....:         self.b = b
   ....:         raise RuntimeError('Cannot create instance of this class')
   ....:

In [13]: class B(A):
   ....:     pass
   ....:

In [14]: c=B(2)

What I want from this example, is to be able to initiate the B subclass, call c.b and retrieve 2. If I would call the A class, it would give me the RuntimeError. The problem with this implementation is that it will raise the error on B as well. How can I get around this?

One solution, as some commented, is to place the self.b = b part in the subclass and overwrite the __init__ function. I would prefer to leave the code in the superclass if possible, since this will be duplicated quite in quite a few subclasses otherwise.

Thanks.

Upvotes: 0

Views: 366

Answers (2)

Taar
Taar

Reputation: 828

What's wrong with this:

class A(object):
    def __init__(self, b):
        self.b = b
        if type(self) == A:
            raise NotImplementedError('Cannot create instance of this class')

class B(A):
    pass

B(2) # doesn't raise
A(2) # raises

Upvotes: 1

unutbu
unutbu

Reputation: 880547

import abc

class A(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def __init__(self, b):
        pass

class B(A):
    def __init__(self, b):
        self.b = b

c = A(2)

Upvotes: 1

Related Questions