示例工程 02-syntax-c-go-java
02-syntax-c-go-java/01-truthiness-table/truthiness_table.py
"""演示 Python 的真值性与自定义 __bool__。"""
from __future__ import annotations
class Flag:
"""按构造参数决定真值的对象。"""
def __init__(self, truth: bool) -> None:
self.truth = truth
def __bool__(self) -> bool:
return self.truth
def truthiness(values: list[object]) -> list[bool]:
"""返回每个值的 bool() 结果。"""
return [bool(value) for value in values]
def samples() -> dict[str, object]:
"""覆盖常见假值与真值。"""
return {
"None": None,
"0": 0,
"0.0": 0.0,
"''": "",
"[]": [],
"{}": {},
"[0]": [0],
"'0'": "0",
"object": object(),
"Flag(False)": Flag(False),
"Flag(True)": Flag(True),
}
def main() -> None:
for name, value in samples().items():
print(f"{name:>10}: {bool(value)}")
if __name__ == "__main__":
main()