Making Classes Subclassable

Ian Kelly ian.g.kelly at gmail.com
Tue Jul 5 10:52:16 EDT 2016


On Mon, Jul 4, 2016 at 1:57 AM, dieter <dieter at handshake.de> wrote:
> Lawrence D’Oliveiro <lawrencedo99 at gmail.com> writes:
>
>> Some of the classes in Qahirah, my Cairo binding <https://github.com/ldo/qahirah> I found handy to reuse elsewhere, for example in my binding for Pixman <https://github.com/ldo/python_pixman>. Subclassing is easy, but then you need to ensure that operations inherited from the superclass return instances of the right class. This means that superclass methods must never refer directly to the class by name for constructing new objects; they need to obtain the current class by more indirect means.
>
> --> "type(obj)" or "obj.__class__" (there are small differences)
> give you the type/class of "obj".

Another option is a classmethod factory:

class X:
    @classmethod
    def new(cls, *args, **kwargs):
        return cls(*args, **kwargs)

    def method(self):
        return self.new()

class Y(X): pass

Y().method() will return a new Y instance. There's not a lot of reason
to prefer this over type(self)(), but by overriding the classmethod
you can have subclasses that use different signatures in the
constructor but still support the same signature in the factory for
compatibility with the base class. You can also make the classmethod
private, if you wish.



More information about the Python-list mailing list