[英]Python - How can I call methods of super class from child class instance?
When child class has a method with same name with the method in parent class, the method of child class overrides the method of parent class.当子 class 具有与父 class 中的方法同名的方法时,子 class 的方法将覆盖父 ZA2F2ED4F8EBC2CBBZ4 的方法。
In the definition of child class, it is possible to access the method of parent class by super()
.在子 class 的定义中,可以通过
super()
访问父 class 的方法。
Then, Does it possible to access the method of parent class from child class Instance?那么,是否可以从子 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
If there is absolutely no way to access the parent class in any other way, I guess you could do this, but I would absolutely not recommend it:如果绝对没有办法以任何其他方式访问父 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"
You have to understand that this is super hacky, and that you are not calling the method of an instance, as it is the case with s.print()
, but you are calling the method of an uninstantiated class, a method that is not a classmethod
(or staticmethod
for that matter) and pass it the class as an argument (ie the self
argument).您必须了解这是超级hacky,并且您没有调用实例的方法,就像
s.print()
的情况一样,但是您正在调用未实例化的 class 的方法,该方法不是一个类方法(或就此而言的staticmethod
方法)并将classmethod
作为参数(即self
参数)传递给它。 It's very different syntax.这是非常不同的语法。
And again, it makes much more sense to give the methods different names instead of overriding them.再一次,给方法赋予不同的名称而不是覆盖它们更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.