Disallowing instantiation of super class

Irv Kalb Irv at furrypants.com
Thu Feb 23 19:19:04 EST 2017


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.

I would like to add is some "insurance" that I (or someone else who uses my code) never instantiates my Base class,  It is not intended to be instantiated because some of the needed instance variables are only created in the __init__ method of ClassA and ClassB.  I am looking for some way in the Base's __init__ method to determine if the method was called directly:

    instanceOfBase = Base(... some data ...)  # I want this case to generate an error

I tried using "isinstance(self, Base)", but it returns True when I instantiate an object from ClassA, from ClassB, or from Base.  

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

Thanks,

Irv

(If it makes a difference, I am doing this currently in Python 2.7 - please don't beat me up about that.)


More information about the Python-list mailing list