Python - 如何从子 class 实例调用超级 class 的方法?

Python - How can I call methods of super class from child class instance?

当子 class 有一个与父 class 中的方法同名的方法时,子 class 的方法覆盖父 class 的方法。

在子class的定义中,可以通过super()访问父class的方法。

那么,是否可以从子class实例访问父class的方法?

class Person:
    def print(self):
        print("Message from Person")

class Student(Person):
    def print(self):
        print("Message from Student")\

s = Student()
# Method of Student Class Instance
s.print()  # Output: "Message from Student"

# I want to call method "print" of Person
# from student Instance
# How can I call it?
s.super().print()  # ERROR
super(s).print()  # ERROR

如果绝对没有办法以任何其他方式访问父 class,我想你可以这样做,但我绝对 推荐它:

class Person:
    def print(self):
        print("Message from Person")


class Student(Person):
    def print(self):
        print("Message from Student")


s = Student()
# Method of Student Class Instance
s.print()  # Output: "Message from Student"
s.__class__.__base__.print(s.__class__.__base__)  # Output: "Message from Person"

你必须明白这是超级 hacky,你不是在调用实例的方法,就像 s.print() 的情况一样,而是调用未实例化的方法 class,一种不是 classmethod(或 staticmethod 的方法)并将 class 作为参数传递给它(即 self 参数)。这是非常不同的语法。

同样,给方法不同的名称而不是覆盖它们更有意义。