给出以下功能:
def httpstatus(self, url, data=None, timeout=None):
if timeout is None:
timeout = socket._GLOBAL_DEFAULT_TIMEOUT
urlopen(url, data, timeout)
timeout参数应该是可选的。但是,如果ommited我想使用socket._GLOBAL_DEFAULT_TIMEOUT值,如代码所示。但是,那个是受保护的成员。这似乎不是正确的方法。如此不同的方法......
def httpstatus(self, url, data=None, timeout=None):
if timeout is None:
urlopen(url, data)
else:
urlopen(url, data, timeout)
是的,那个人更脏......
什么是回退到套接字默认超时的正确和正确的方法?
答案 0 :(得分:1)
您可以使用**
-syntax:
def httpstatus(self, url, data=None, timeout=None):
kwargs = {}
if timeout is not None:
kwargs['timeout'] = timeout
urlopen(url, data, **kwargs)
甚至:
def httpstatus(self, url, data=None, **kwargs):
# Don't forget to mention in documentation that all
# extra arguments are passed to urlopen as is.
urlopen(url, data, **kwargs)
答案 1 :(得分:1)
如果你真的不想使用protected var,只需从套接字中获取数字并从中获取注释:
# settings
default_timeout = 100 # socket._GLOBAL_DEFAULT_TIMEOUT
另一种选择是使用getattr
默认值:
default_timeout = getattr(socket, '_GLOBAL_DEFAULT_TIMEOUT', 100)
def httpstatus(self, url, data=None, timeout=default_timeout):
urlopen(url, data, timeout)