Disallowing instantiation of super class

Irv Kalb Irv at furrypants.com
Thu Feb 23 23:53:15 EST 2017


> On Feb 23, 2017, at 4:40 PM, MRAB <python at mrabarnett.plus.com> wrote:
> 
> On 2017-02-24 00: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.
>> 
>> 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.)
>> 
> Apart from renaming Base to _Base as a hint, you could put Base's initialisation code in, say, '_init' and have Base's __init__ just raise an exception.
> 
> ClassA and ClassB would then call Base's _init instead of its __init__.
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

MRAB and Peter:  Thank you very much for your solutions.  I had considered both of these, but was wondering if there was another way.   Peter's solution does exactly what I want, but I'm not ready to get into metaclasses.  So I decided to go with MRAB's approach.  I've modified my code and it seems to work great.

Thank you both.

Irv




More information about the Python-list mailing list