Skip to main content
 首页 » 编程设计

python之调用方法时如何访问父方法

2025年01月19日8over140

如何在 python 中使用函数覆盖访问父方法? 请参见下面的示例:

class Parent:       
   def myMethod(self): 
      print 'Calling parent method' 
 
class Child(Parent): 
   def myMethod(self): 
      print 'Calling child method' 
 
c = Child()         
c.myMethod() 

这是一个合适的功能覆盖解决方案吗?

请您参考如下方法:

你需要定义Parent作为新型类(class):Parent(object)并使用 super(Child, self).myMethod()在 Child . Pyfiddle

class Parent(object):       
   def myMethod(self): 
      print 'Calling parent method' 
 
class Child(Parent): 
   def myMethod(self): 
      super(Child, self).myMethod() 
      print 'Calling child method' 
 
c = Child() 
c.myMethod()