![](/img/trans.png)
[英]Python - difference between self.method, lambda: self.method() and self.method() on startup
[英]What's the difference between super().method() and self.method()
当我们从父类继承某些东西时,为什么使用super().method()
和self.method()
什么区别,为什么要使用一个而不是另一个呢?
我唯一想到的是,使用静态方法显然无法调用self.method()
。 至于其他一切,我无法提出使用super()
理由。
当有人选择另一个问题时,有人可以提出一个虚拟的例子,并解释原因,还是仅仅是常规的事情?
即使孩子定义了自己的method
, super().method()
也会调用super().method()
的父类实现。 您可以阅读super
的文档以获得更深入的解释。
class Parent:
def foo(self):
print("Parent implementation")
class Child(Parent):
def foo(self):
print("Child implementation")
def parent(self):
super().foo()
def child(self):
self.foo()
c = Child()
c.parent()
# Parent implementation
c.child()
# Child implementation
对于像Child
这样的单继承类, super().foo()
与更明确的Parent.foo(self)
。 在多重继承的情况下, super
将根据“ 方法解析顺序”或MRO确定要使用的foo
定义。
另一个有启发性的示例:如果我们将Child
子类化并编写foo
另一个实现,则调用哪个方法?
class Grandchild(Child):
def foo(self):
print("Grandchild implementation")
g = Grandchild()
g.parent()
# Parent implementation
g.child()
# Grandchild implementation
自
self ,通常用作类的实例方法的第一个参数,它始终表示类的调用对象/实例。
超()
super()引用父类的对象。 在方法重写和多语言(包括C ++,Java等)编程的情况下,此方法很有用。在Java中, super()用于调用父类的构造函数。
请看下面的小例子。
class TopClass(object):
def __init__(self, name, age):
self.name = name;
self.age = age;
def print_details(self):
print("Details:-")
print("Name: ", self.name)
print("Age: ", self.age)
self.method()
def method(self):
print("Inside method of TopClass")
class BottomClass(TopClass):
def method(self):
print("Inside method of BottomClass")
def self_caller(self):
self.method()
def super_caller(self):
parent = super()
print(parent)
parent.method()
child = BottomClass ("Ryan Holding", 26)
child.print_details()
"""
Details:-
Name: Ryan Holding
Age: 26
Inside method of BottomClass
"""
parent = TopClass("Rishikesh Agrawani", 26)
parent.print_details()
"""
Details:-
Name: Rishikesh Agrawani
Age: 26
Inside method of TopClass
"""
child.self_caller()
child.super_caller()
"""
Inside method of BottomClass
<super: <class 'BottomClass'>, <BottomClass object>>
Inside method of TopClass
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.