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