[英]python multiple inheritance calling overridden functions in super context
(Python 3) (蟒蛇 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?我怎样才能让 newclass.print_goober() 首先在其自身上下文中调用 print_blob() ,然后在 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
.所以......
self
很好...... self
。 In your example, every time you call self
, it is the instance of Markdown
that is known on the outside as newclass
.在你的榜样,每次通话时间
self
,它的实例Markdown
是在外面已知newclass
。
When you think of it this way, self.print_thing
does what you would expect it to.当你这样想时,
self.print_thing
会做你期望的事情。 It looks for the first print_thing
method it can find and then calls it with self
as the first argument.它查找它可以找到的第一个
print_thing
方法,然后以self
作为第一个参数调用它。
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:在这种情况下,我建议让
markdown
定义调用旧方法的新方法:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.