如何将 bool 值作为参数传递给方法?
例如,我有如下代码:
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):
...
因为我从 invoke_tls
方法中将 starttls
作为字符串传递,在方法定义 invoke_tls
中,如果 require_tls
是默认情况下未设置为 bool 值 False,starttls
被视为“True”(字符串)
如果有一种方法可以在 python 中将 bool 类型作为可选参数传递,请告诉我。
我知道一种方法是在 if else 条件下处理字符串并按如下方式处理:
def t_or_f(arg):
ua = str(arg).upper()
if 'TRUE'.startswith(ua):
return True
elif 'FALSE'.startswith(ua):
return False
但是,如果有任何其他有效或更好的方法将 bool 值作为输入传递给另一种方法,请告诉我?
最佳答案
True
或 False
值没有什么特别的...
invoke_tls(self, auth_type, auth_value, starttls)
如果你的意思是如何传递特定参数而不是其他参数,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
Python 还允许动态指定关键字参数...例如
parms = {"c" : True} # Dictionary name → value
foo(1, **parms) # b will be 1 (default), c will be True
关于python - 将 bool 值作为输入传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356957/