Disallowing instantiation of super class

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri Feb 24 05:21:00 EST 2017


On 24.02.2017 01:19, Irv Kalb wrote:
> Hi,
> I have built a set of three classes:
> -  A super class, let's call it: Base
>
> -  A class that inherits from Base, let's call that: ClassA
>
> -  Another class that inherits from Base, let's call that: ClassB
>
> ClassA and ClassB have some code in their __init__ methods that set some instance variables to different values.  After doing so, they call the the __init__ method of their common super class (Base) to set some other instance variables to some common values.  This all works great.  Instances of ClassA and ClassB do just what I want them to.
>

[...]
>
> If I can find a way to determine that the caller is attempting to instantiate Base directly, I will raise an exception.
>

A pattern I'm using sometimes to achieve this is:

class Base:
     def __init__(self):
         self.set_common()
         self.set_specific()

     def set_common(self):
         self.a = 10

     def set_specific(self):
         raise NotImplementedError()


class A(Base):
     def set_specific(self):
         self.b = 20


class B(Base):
     def set_specific(self):
         self.b = 30


Of course, MRAB's and Peter's suggestion are very similar ideas.




More information about the Python-list mailing list