[Tutor] creating a subclass from superclass without __init__

Steven D'Aprano steve at pearwood.info
Fri Aug 24 21:01:44 CEST 2012


On 25/08/12 04:22, Matt Gregory wrote:
> Is it possible to create a subclass of a superclass that doesn't have an
>__init__ and is only created through another class.
> Here is an example of what isn't working:
>
> class Spam(object):
>     def __new__(cls, *args):
>         return super(Spam, cls).__new__(cls, args)
>     def __init__(self):
>         raise AttributeError('Cannot create Spam')

That will prevent anything from successfully initialising a Spam
instance. It doesn't prevent anything from creating a Spam instance,
only initialising it. Anyone can simply call Spam.__new__ directly,
and bypass the booby-trap in __init__.

Why do you want to do this?


> class SubSpam(Spam):
>     def __new__(cls, *args):
>         return SpamMaker().make_spam()

While it is legal for a class __new__ method to return an instance
of a different class, that should be considered very unusual. Why
do you want SubSpam(*args) to return a Spam instance instead of a
SubSpam instance?


>     def test(self):
>         print 'This is a SubSpam class'



[...]
> My real use case is using the Python bindings to GDAL and trying
>to create a subclass of gdal.Band which can't be instantiated
>directly.

That's not a use-case. A use-case is a real-world problem that you
are trying to solve. You have skipped the problem and jumped straight
to what you think is the solution: "create a subclass which can't be
instantiated directly".

I can't imagine any problem where the solution to the problem depends
on whether or not you instantiated a subclass using:

Spam(*args)

or

SpamMaker.make(*args)


Why do you care if Spam is called directly?




-- 
Steven


More information about the Tutor mailing list