如何将boolean作为参数传递给方法?
例如,我有一个代码如下:
def msg_util(self, auth_type=None,starttls=False):
....
starttls=True
invoke_tls(self, auth_type, auth_value, "require_tls=%s" %starttls)
....
....
def invoke_tls(self, auth_type=None, auth_value=None,range=None,style=None, adminuser=None,require_tls=False):
...
Run Code Online (Sandbox Code Playgroud)
由于我starttls
从invoke_tls
方法传递为字符串,因此在方法定义中invoke_tls
,如果require_tls
默认情况下未设置为boolean False ,则将其starttls
视为"True"(字符串)
如果有一种方法可以将boolean类型作为python中的可选参数传递,请告诉我.
我知道一种方法是在if else条件下处理字符串并按如下方式处理它:
def t_or_f(arg):
ua = str(arg).upper()
if 'TRUE'.startswith(ua):
return True
elif 'FALSE'.startswith(ua):
return False
Run Code Online (Sandbox Code Playgroud)
但是,如果有任何其他有效或更好的方法将布尔值作为输入传递给另一个方法,请告诉我?
没有什么特别的True
或False
价值观......
invoke_tls(self, auth_type, auth_value, starttls)
Run Code Online (Sandbox Code Playgroud)
如果你的意思是如何传递特定参数而不是其他参数,Python有"关键字参数":
def foo(a, b=1, c=False):
print(a, b, c)
foo(1) # b will be 1 and c False (default values)
foo(1, c=True) # b will be 1 (default) and c True
Run Code Online (Sandbox Code Playgroud)
Python还允许动态指定关键字参数...例如
parms = {"c" : True} # Dictionary name ? value
foo(1, **parms) # b will be 1 (default), c will be True
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28523 次 |
最近记录: |