简体   繁体   中英

python multiple inheritance calling overridden functions in super context

(Python 3)

I'm trying to extend a class with some fancy new formatting routines, however I'd also like to be able to use the formatting routines in the base class.

class Plaintext(object):
    def print_thing(self, thing):
        print("plain", thing)

    def print_blob(self, blob):
        for thing in blob:
            self.print_thing(thing)

    def print_goober(self, blob):
        print("plaintext")
        self.print_blob(blob)

class Markdown(Plaintext):
    def print_thing(self, thing):
        print("mark", thing)

    def print_goober(self, blob):
        print("markdown")
        self.print_blob(blob)
        super().print_blob(blob)

newclass = Markdown()
newclass.print_goober([1,2,3])

When run, I get:

markdown
mark 1
mark 2
mark 3
mark 1
mark 2
mark 3

How can I get newclass.print_goober() to call print_blob() first in its self context and then in the context of BaseClass?

The output I was trying to get was:

markdown
mark 1
mark 2
mark 3
plain 1
plain 2
plain 3

Do I need to create some sort of mixin thing?

So ... self is well ... self . In your example, every time you call self , it is the instance of Markdown that is known on the outside as newclass .

When you think of it this way, self.print_thing does what you would expect it to. It looks for the first print_thing method it can find and then calls it with self as the first argument.

Alright, now that we have that sorted ... How do we do what you want to do? Well, (and I can't say this strongly enough) there's no clean way to do it without being more explicit about what you actually want. In this case, I'd recommend having markdown define new methods that call the old ones:

class Plaintext(object):
    def print_thing(self, thing):
        print("plain", thing)

    def print_blob(self, blob):
        for thing in blob:
            self.print_thing(thing)

    def print_goober(self, blob):
        print("plaintext")
        self.print_blob(blob)

class Markdown(Plaintext):
    def print_markdown_thing(self, thing):
        print("mark", thing)

    def print_markdown_blob(self, blob):
        for thing in blob:
            self.print_markdown_thing(thing)

    def print_goober(self, blob):
        print("markdown")
        self.print_markdown_blob(blob)
        self.print_blob(blob)

newclass = Markdown()
newclass.print_goober([1,2,3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM