Python 从子级调用super方法时,何时使用self、super()和类名?
Python 从子级调用super方法时,何时使用self、super()和类名?,python,Python,super().method()和ClassName.method()做同样的事情,但是什么时候使用super().method()vsself.method() 根据我的理解,当从同一方法调用super方法时,将使用super().method(),而从子类的其他方法调用时,将使用self.method() class Animal(): def运行(自): 打印('正在运行') def步行(自我): 打印('walking') 类别猫(动物): def运行(自): super().run()
super().method()
和ClassName.method()
做同样的事情,但是什么时候使用super().method()
vsself.method()
根据我的理解,当从同一方法调用super方法时,将使用super().method()
,而从子类的其他方法调用时,将使用self.method()
class Animal():
def运行(自):
打印('正在运行')
def步行(自我):
打印('walking')
类别猫(动物):
def运行(自):
super().run()
def步行快速(自我):
self.walk()-->super().walk()也可以,但有什么理由使用其中一个而不是另一个?
c=猫()
c、 运行()
c、 快走
super()
引用父类,而self.method()
执行类本身的方法
由于Cat
继承自Animal
,c.run()
应该打印running
但是,您不必在Cat
中重新定义run()
函数,因为它已经从Animal
继承了方法c.run()
将已打印running
类似地,self.walk()
正在运行您的函数,因为它是在Animal
中定义的,Cat
继承自Animal
super()
通常与\uuuu init\uuuuu()
一起使用,您希望在子类中初始化父类的属性。请查看以了解更多详细信息。下面的代码应该会让您明白
class Animal():
def run(self):
print('running')
def walk(self):
print('Animal is walking')
#Static method called walk
@staticmethod
def static_walk():
print('Animal is walking in static')
class Cat(Animal):
def run(self):
super().run()
def walk(self):
print('Cat is walking')
def walk_fast(self):
#This calls walk of Animal
super().walk()
#This calls walk of Cat
self.walk()
#This calls static method walk of Animal
Animal.static_walk()
输出将是
running
Animal is walking
Cat is walking
Animal is walking in static
,Cat().walk\u fast()
将调用super().walk()
类的Animal
,因此您可以看到walk
Animal is walking
- 执行
将调用超类的方法,如果它在超类中实现super().method()
self.walk()
调用类本身的方法self.method()
- 执行
将调用类的ClassMethod.method()
方法,因此static
和super().method()
是不同的ClassName.method()
将调用Animal.static\u walk()
类的static方法,因此您可以看到Animal
Animal在static中行走
super()
是对父类的引用。它通常与描述符和神奇方法一起使用,如\uuuu init\uuuu
。它允许您直接从父类调用方法,而无需定义父类名称。它还允许您在mro
使用self与使用self没有直接区别,除非与方法的名称冲突,即
class Animal():
def run(self):
print('running')
def walk_fast(self):
print('walking')
class Cat(Animal):
def run(self):
super().run()
def walk_fast(self):
super(Cat).walk_fast()
print('After walking')
c = Cat()
c.run()
c.walk_fast()
事实上,这个名字解释了一切,如果你用这种方式编写代码,你可以看到区别
class Animal:
def run(self):
print('running')
def walk(self):
print('walking')
class Cat(Animal):
def run(self):
# override to make a difference between self.run() and super().run()
print('running like a cat')
def run_super(self):
super().run()
def run_self(self):
self.run()
c = Cat()
c.run() # running like a cat
c.run_super() #running
c.run_self() # running like a cat
c.walk() # Cat don't have walk, call go to Animal (e.g. super())
如果在
Cat()
中创建方法walk()
,则self.walk()
仍将正常工作。如果从Animal()
中删除walk()
,并将walk()
保留在Cat()
中,则self.walk()
仍能正常工作。它允许您访问通过重新定义名称而隐藏的类方法。这三种方法都是ClassName.method
super().method
和self().method
彼此不同@KetanPatel,请检查下面的答案!谢谢gkhnavarro,谢谢Bill的澄清。我现在明白超级的目的了。太好了!很高兴帮助你:如果我的答案对你有帮助,请考虑把它标记为点击答案旁边的嘀嗒声“凯坦帕特尔:”。