Disallowing instantiation of super class

Peter Otten __peter__ at web.de
Thu Feb 23 19:58:45 EST 2017


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.)

>>> import abc
>>> class Base:
...     __metaclass__ = abc.ABCMeta
...     @abc.abstractmethod
...     def __init__(self):
...         self.z = self.x + self.y
... 
>>> class A(Base):
...     def __init__(self):
...         self.x = 2
...         self.y = 3
...         super(A, self).__init__()
... 
>>> A().z
5
>>> Base()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Base with abstract methods 
__init__





More information about the Python-list mailing list