简体   繁体   English

Python函数总是返回相同的布尔值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM