[英]Python function that always return the same boolean value
In functional programming is sometimes useful to have a function that always return True
(or False
) for every parameter (or even multiple parameters). 在函数式编程有时是非常有用的一个功能,总是返回
True
(或False
的每一个参数(甚至多个参数))。
Is there a built-in or a function defined in some module that have this exact behaviour? 是否有某个模块中定义的内置函数或函数具有这种确切的行为?
I'm not aware of any built-in, but you can define them as: 我不知道任何内置,但您可以将它们定义为:
false = lambda *_: False
true = lambda *_: True
You can use object
, since its instances will always be treated as a true value, since object
defines neither __len__
, __nonzero__
(in Python 2), nor __bool__
(in Python 3). 可以使用
object
,因为它的实例将总是作为一个真正的值被处理,因为object
定义既不__len__
, __nonzero__
(在Python 2),也不__bool__
(在Python 3)。
>>> bool(object())
True
>>> if object():
... print("Hi")
...
Hi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.