Disallowing instantiation of super class
MRAB
python at mrabarnett.plus.com
Fri Feb 24 13:40:38 EST 2017
On 2017-02-24 09:24, Steve D'Aprano wrote:
> On Fri, 24 Feb 2017 11:19 am, Irv Kalb wrote:
>
>> Hi,
>>
>> I have built a set of three classes:
>>
>> - A super class, let's call it: Base
> [...]
>> 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.
>
> class Base:
> def __init__(self):
> if type(self) is Base:
> raise TypeError("cannot instantiate Base class")
>
>
> Does that help?
>
D'oh! Never thought of that! :-)
The OP is using Python 2.7, so you'll need to use new-style classes:
class Base(object):
def __init__(self):
if type(self) is Base:
raise TypeError("cannot instantiate Base class")
More information about the Python-list
mailing list