[英]How to make **kwargs optional
I have two classes that have a method with the same name, but this method uses different parameters. 我有两个类具有相同名称的方法,但此方法使用不同的参数。 So I thought about using
**kwargs
(see example below). 所以我想到了使用
**kwargs
(见下面的例子)。 But one of the two methods does not require any parameter, so I get this error: 但是这两种方法中的一种不需要任何参数,所以我得到这个错误:
TypeError: print_smt() takes 1 positional argument but 2 were given
TypeError:print_smt()占用1个位置参数,但给出了2个
because it is passing an empty dictionary to the function, I suppose. 因为我想将空字典传递给函数。
How can I solve this problem? 我怎么解决这个问题? Am I forced to use an
if
statement to call the function with and without parameters, or there is a better way to solve the problem? 我是否被迫使用
if
语句来调用带有和不带参数的函数,或者有更好的方法来解决问题?
class Bar(object):
def print_smt(self, text):
print(text)
class Foo(object):
def print_smt(self):
print("Nothing")
def test(obj, **p2):
obj.print_smt(p2)
bar = Bar()
test(bar, text='print this')
foo = Foo()
test(foo) # This one breaks!
When you call: 你打电话时:
def test(obj, **p2):
obj.print_smt(p2)
...you're passing a dictionary to print_smt()
. ...你正在将字典传递给
print_smt()
。 Even if it's an empty dictionary, it's still a dictionary, and you can't pass a dictionary as an argument to something that takes no arguments. 即使它是一个空字典,它仍然是一个字典,你不能将字典作为参数传递给不带参数的东西。
If you want to pass through keyword arguments as keyword arguments , rather than as a single positional argument with a dictionary, then do so: 如果要将关键字参数作为关键字参数传递,而不是作为带字典的单个位置参数,则执行以下操作:
def test(obj, **p2):
obj.print_smt(**p2)
You have to unpack the kwargs before passing it to the print_smt function. 你必须在将kwargs传递给print_smt函数之前解压缩它。 This works:
这有效:
def test(obj, **p2):
obj.print_smt(**p2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.