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

00_*_*_00 2 python oop inheritance class

我正在用python编写一个类。

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

然后我想扩展这个类:

class my_extended_class(my_class):
Run Code Online (Sandbox Code Playgroud)

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

我可以吗:

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
Run Code Online (Sandbox Code Playgroud)

2)“直接”调用父方法?

def foo(self,*args,**kwargs):
    my_class.foo(*args,**kwargs)
    # other child-specific statements
    return self
Run Code Online (Sandbox Code Playgroud)

3)其他可能的方式?

avi*_*gil 6

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
Run Code Online (Sandbox Code Playgroud)

兼容性在如何调用 super() 所以它在 2 和 3 中兼容?但简而言之,Python 3 支持super使用或不使用 args调用,而 Python 2 需要它们。