Python 将布尔值作为方法的输入传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41356957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass boolean values as input to method
提问by Arun Shankar
How do I pass boolean as argument to a method ?
如何将布尔值作为参数传递给方法?
For example, I have a code as below:
例如,我有一个代码如下:
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):
...
Since am passing starttls
as string from invoke_tls
method, in the method definition invoke_tls
, if require_tls
is not set to boolean False by default, starttls
is taken as "True" (string)
由于我starttls
从invoke_tls
方法中作为字符串传递,在方法定义中invoke_tls
,如果require_tls
默认情况下未设置为布尔值 False ,则将其starttls
视为“True”(字符串)
Please let me know if there is a way I can pass boolean type as optional parameters in python.
请让我知道是否有办法在 python 中将布尔类型作为可选参数传递。
I know that one way is to process the string in if else condition and process it as below:
我知道一种方法是在 if else 条件下处理字符串并按如下方式处理它:
def t_or_f(arg):
ua = str(arg).upper()
if 'TRUE'.startswith(ua):
return True
elif 'FALSE'.startswith(ua):
return False
But, please let me know if there is any other effective or better way to pass boolean values as input to another method ?
但是,请让我知道是否有任何其他有效或更好的方法将布尔值作为输入传递给另一种方法?
回答by 6502
There's nothing special about True
or False
values...
没有什么特别之处True
或False
价值观...
invoke_tls(self, auth_type, auth_value, starttls)
If what you mean is how to pass specific parameters but not others, Python has "keyword parameters":
如果你的意思是如何传递特定参数而不是其他参数,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 also allows to specify keyword arguments dynamically... for example
Python 还允许动态指定关键字参数......例如
parms = {"c" : True} # Dictionary name → value
foo(1, **parms) # b will be 1 (default), c will be True
回答by MYGz
Boolean is a data type and can be passed around as any other data type.
Boolean 是一种数据类型,可以像任何其他数据类型一样传递。
Check:
查看:
a = True
def foo(b=None):
print b
foo(a)
Output:
输出:
True