繁体   English   中英

如何在python中调用父类方法?

[英]how to call parent class methods in python?

我正在用python编写类。

class my_class(object):
    def __init__(self):
    # build my objects 
    def foo(self,*args,**kwargs):
    # do something with them

然后,我想扩展此类:

class my_extended_class(my_class):

但是我无法弄清楚访问父方法的正确方法是什么。

我可以吗:

1)创建一个父亲对象的实例? 在构造器时

def __init__(self):
    self.my_father=my_class()
    # other child-specific statements
    return self
def foo(self,*args,**kwargs):
    self.my_father.foo(*args,**kwargs)
    # other child-specific statements
    return self

2)称父方法为“直接”吗?

def foo(self,*args,**kwargs):
    my_class.foo(*args,**kwargs)
    # other child-specific statements
    return self

3)其他可能的方式?

使用super(ClassName, self)

class my_class(object):
    def __init__(self):
    # build my objects 
    def foo(self,*args,**kwargs):
    # do something with them

class my_extended_class(my_class):
    def foo(self,*args,**kwargs):
        super(my_extended_class, self).foo(*args,**kwargs)
        # other child-specific statements
        return self

如何调用super()讨论兼容性,以便它在2和3中兼容? 简而言之,Python 3支持在有或没有args的情况下调用super ,而Python 2需要它们。

您可以使用super()方法。 例如:

class my_extended_class(my_class):
   def foo(self,*args,**kwargs):
      #Do your magic here 
      return super(my_extended_class, self).foo(self,*args,**kwargs)

您可能会转到此链接并找到其他答案。

在Python中从子类调用父类的方法?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM