如何将这两个功能与使用可选参数的功能结合在一起?

时间:2019-01-18 17:46:18

标签: python function

以下两个功能几乎相同:

def http_get(url):
    with urllib.request.urlopen(url) as w:
        return w.read()

def http_post(url, params):
    with urllib.request.urlopen(url, params) as w:
        return w.read()

我可以使用变长参数列表或可选参数来组合它们,以便可以使用一个或两个参数来调用它,并使它执行正确的操作吗?

2 个答案:

答案 0 :(得分:0)

def http_get(url, params=None):
    with urllib.request.urlopen(url, params) as w:
        return w.read()

答案 1 :(得分:0)

if you're passing all the arguments directly, you could argue that you should just use *args.

def http_get(*args):
    with urllib.request.urlopen(*args) as w:
        return w.read()

http_post = http_get