[Python-ideas] The prohibition overrides the class method

Michael Selik mike at selik.org
Mon Nov 16 19:12:58 EST 2015


Thanks, Ian, I missed that detail.

While my initial thought was that name mangling would achieve the desired
level of subclassing-clumsiness defense. As below...

    # using 2 steps instead of 3, for brevity

    class Envelope:
        def prepare(self):
            print('omnibus!')

    class Child(Envelope):

        def stuff(self):
            print('step 1')
        __stuff = stuff

        def seal(self):
            print('step 2')
        __seal = seal

        def prepare(self):
            self.__stuff()
            self.__seal()


The post on StackExchange added the extra wrinkle that both classes have
C++ virtual functions, kind-of like this...

    from abc import ABC, abstractmethod

    class Envelope(ABC):

        def something_useful(self):
            ''' I'd normally avoid tricky inheritance
            but there must be some really useful code
            in here that I don't want to refactor
            '''

        @abstractmethod
        def prepare(self):
            pass


    class Child(Envelope):

        @abstractmethod
        def stuff(self):
            print('step 1')

        @abstractmethod
        def seal(self):
            print('step 2')

        def prepare(self):
            'should be FINAL, Override at your OWN PERIL'
            self.stuff()
            self.seal()

This contrived scenario seems better resolved by refactoring the `Envelope`
class. Moreover, I don't understand why the `Child` class would exist at
all. Why override `prepare` only to create more abstract methods?

On Mon, Nov 16, 2015 at 6:40 PM Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Nov 16, 2015 4:15 PM, "Michael Selik" <mike at selik.org> wrote:
> >
> > For that envelopes example on StackExchange, I'd probably use name
> mangling to reduce chances of subclassing mistakes and have prepare() call
> stuff(), seal(), stamp() in the correct order or whatever those were. I'm
> not sold in the need for "final".
>
> Name mangling would not work in that example. The prepare method is
> defined by a base class and overridden in a subclass; it is the subclass
> that wishes to declare the method final. Name mangling would obstruct
> overriding the method at all, which would be a problem for the base class
> that invites the method to be overridden.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151117/36fffbb2/attachment.html>


More information about the Python-ideas mailing list