在python中,是否存在某种类型的映射可返回"False value"?类型的? [英] In python, is there some kind of mapping to return the "False value" of a type?
问题描述
我正在寻找某种类似于以下功能的映射函数 f()
:
I am looking for some kind of a mapping function f()
that does something similar to this:
f(str) = ''
f(complex) = 0j
f(list) = []
意味着它返回类型为强制转换为 bool
的 False
的对象.
Meaning that it returns an object of type that evaluates to False
when cast to bool
.
这样的功能存在吗?
推荐答案
不,没有这样的映射.并非每种类型的对象都有虚假的值,而其他类型则有多个.由于可以使用 __ bool __
方法,从理论上讲,一个类可以具有无限数量的(不同的)虚假实例.
No, there is no such mapping. Not every type of object has a falsy value, and others have more than one. Since the truth value of a class can be customized with the __bool__
method, a class could theoretically have an infinite number of (different) falsy instances.
也就是说,大多数内置类型在不带参数的情况下调用其构造函数时会返回其伪造的值:
That said, most builtin types return their falsy value when their constructor is called without arguments:
>>> str()
''
>>> complex()
0j
>>> list()
[]
这篇关于在python中,是否存在某种类型的映射可返回"False value"?类型的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!