gpt4 book ai didi

python - 向重写方法添加关键字参数并使用 **kwarg

转载 作者:太空狗 更新时间:2023-10-29 17:29:02 25 4
gpt4 key购买 nike

我正在对一个对象进行子类化,以便覆盖我想添加一些功能的方法。我不想完全替换它或添加一个不同命名的方法,而是通过向方法添加一个可选参数来保持与父类(super class)方法的兼容。是否可以使用 *args**kwargs 将所有参数传递给父类(super class)并仍然添加一个带有默认值的可选参数?我凭直觉想出了以下方法,但它不起作用:

class A(object):
def foo(self, arg1, arg2, argopt1="bar"):
print arg1, arg2, argopt1

class B(A):
def foo(self, *args, argopt2="foo", **kwargs):
print argopt2
A.foo(self, *args, **kwargs)


b = B()
b.foo("a", "b", argopt2="foo")

当然,当我显式添加父类(super class)方法的所有参数时,我可以让它工作:

class B(A):
def foo(self, arg1, arg2, argopt1="foo", argopt2="bar"):
print argopt2
A.foo(self, arg1, arg2, argopt1=argopt1)

执行此操作的正确方法是什么,我是否必须知道并明确说明所有被覆盖的方法参数?

最佳答案

class A(object):
def foo(self, arg1, arg2, argopt1="bar"):
print arg1, arg2, argopt1

class B(A):
def foo(self, *args, **kwargs):
argopt2 = kwargs.get('argopt2', default_for_argopt2)
# remove the extra arg so the base class doesn't complain.
del kwargs['argopt2']
print argopt2
A.foo(self, *args, **kwargs)


b = B()
b.foo("a", "b", argopt2="foo")

关于python - 向重写方法添加关键字参数并使用 **kwarg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1715840/

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