是否可以使用named和variadic参数调用python 2.7中的实例方法?我喜欢命名参数以便更清楚地读取代码,但似乎这段代码失败了:
def function(bob, sally, *args):
pass
values = [1, 2, 3, 4]
function(bob="Hi bob", sally="Hello sally", *values)
答案 0 :(得分:6)
你可以在命名参数后传递可变参数吗?
Python 3.4.3 :答案是肯定的。
如果要调用仅命名固定参数的函数,请将可变参数放在函数定义中
def function(*args, bob, sally):
print(args, bob, sally)
values = [1, 2, 3, 4]
function(bob="Hi bob", sally="Hello sally", *values)
function(*values, bob="Hi bob", sally="Hello sally")
function(bob="Hi bob", *values, sally="Hello sally")
产生
(1, 2, 3, 4) Hi bob Hello sally
(1, 2, 3, 4) Hi bob Hello sally
(1, 2, 3, 4) Hi bob Hello sally
如您所见,您可以调用函数以您喜欢的任何顺序放置参数。
由于您明确引用了实例方法,因此如果function
是一种方法,比如类A
class A():
def function(self, *args, bob, sally):
print(args, bob, sally)
values = [1, 2, 3, 4]
a=A()
a.function(bob="Hi bob", sally="Hello sally", *values)
a.function(*values, bob="Hi bob", sally="Hello sally")
a.function(bob="Hi bob", *values, sally="Hello sally")
仍然有效并产生
(1, 2, 3, 4) Hi bob Hello sally
(1, 2, 3, 4) Hi bob Hello sally
(1, 2, 3, 4) Hi bob Hello sally
Python 2.7.6 :答案是否定的。
>>> def function(*args, bob, sally):
File "<stdin>", line 1
def function(*args, bob, sally):
^
SyntaxError: invalid syntax
另一种方法可能是为可变参数赋予名称
values = {'p1': 1, 'p2': 2, 'p3': 3, 'p4': 4}
然后你可以定义
def function(bob, sally, **kwargs):
print(kwargs['p1'])
并用
调用它function(bob="Hi bob", sally="Hello sally", **values)
答案 1 :(得分:2)
是的,但稍微修改了你正在做的事情:
def foo(bob="abc", sally="def", **kwargs):
pass
foo(bob="stuff", sally="buff", other_stuff=[1, 2, 3])