使用 Python 中的默认值与输入参数混合
Using default values in Python mixed with input parameters
我的函数如下所示:
def CreateURL(port=8082,ip_addr ='localhost',request='sth'):
return str("http://" + ip_addr+":"+str(port) + '/' + request)
现在我想为 port
和 request
使用默认参数,但不为 ip_addr
使用默认参数。在这种情况下我必须如何编写函数?
CreateURL('192.168.2.1')
不起作用,因为它将覆盖 port
而不是 ip_addr
显式传递参数。
>>> def foo(a=1, b=2, c=3):
... print(a, b, c)
...
>>> foo(c=4)
(1, 2, 4)
url = CreateURL(ip_addr='192.168.2.1')
只需像这样说明您要指定的参数的名称:
>>> CreateURL(ip_addr = '192.168.2.1')
'http://192.168.2.1:8082/sth'
您可以简单地显式传递参数
>>> CreateURL(ip_addr = "192.168.2.1")
'http://192.168.2.1:8082/sth'
我的函数如下所示:
def CreateURL(port=8082,ip_addr ='localhost',request='sth'):
return str("http://" + ip_addr+":"+str(port) + '/' + request)
现在我想为 port
和 request
使用默认参数,但不为 ip_addr
使用默认参数。在这种情况下我必须如何编写函数?
CreateURL('192.168.2.1')
不起作用,因为它将覆盖 port
而不是 ip_addr
显式传递参数。
>>> def foo(a=1, b=2, c=3):
... print(a, b, c)
...
>>> foo(c=4)
(1, 2, 4)
url = CreateURL(ip_addr='192.168.2.1')
只需像这样说明您要指定的参数的名称:
>>> CreateURL(ip_addr = '192.168.2.1')
'http://192.168.2.1:8082/sth'
您可以简单地显式传递参数
>>> CreateURL(ip_addr = "192.168.2.1")
'http://192.168.2.1:8082/sth'