首页 > 解决方案 > 关于子类如何调用超类方法的问题

问题描述

考虑下面代码中的继承:

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)


class Student(Person):
    def m1(self):
        super().printname()

    def m2(self):
        Person.printname(self)

s1 = Student("John", "Doe")
s1.m1()
s1.m2()

为什么在 Python 中有两种方法可以让子类调用超类的方法,比如super().printname()上面Person.printname(self)的例子?

这两种方式有什么区别?

还有另一种调用超类方法的方法吗?

标签: python

解决方案


推荐阅读