gpt4 book ai didi

python - python中如何调用父类的方法?

转载 作者:行者123 更新时间:2023-12-05 08:41:28 24 4
gpt4 key购买 nike

我正在用 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

兼容性在 How can I call super() so it's compatible in 2 and 3? 中讨论但简而言之,Python 3 支持使用或不使用 args 调用 super,而 Python 2 需要它们。

关于python - python中如何调用父类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49569239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com