小编haw*_*k64的帖子

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

我是一个对象的子类,以便覆盖我想要添加一些功能的方法.我不想完全替换它或添加一个不同命名的方法,但只是通过向方法添加一个可选参数来保持与超类方法兼容.是否可以使用*args**kwargs传递超类的所有参数,并仍然添加一个带默认值的可选参数?我直观地想出了以下内容,但它不起作用:

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

当我明确添加超类方法的所有参数时,我可以使它工作:

class B(A):
    def foo(self, arg1, arg2, argopt1="foo", argopt2="bar"):
        print argopt2
        A.foo(self, arg1, arg2, argopt1=argopt1)
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法,我必须知道并明确声明所有重写的方法参数?

python

13
推荐指数
2
解决办法
5304
查看次数

标签 统计

python ×1