社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

模拟“len”和“bool”的Python行为`

Hernan • 5 年前 • 1506 次点击  

请考虑以下代码:

>>> class X:
... pass
...
>>> x = X()
>>> len(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'X' has no len()
>>> bool(x)
True

__len__ 它不起作用。

>>> class Y:
...   def __len__(self):
...     raise TypeError
...
>>> y = Y()
>>> len(y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __len__
TypeError
>>> bool(y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __len__
TypeError

有没有办法写一个 像这样工作的函数没有实现?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54216
 
1506 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Martijn Pieters
Reply   •   1 楼
Martijn Pieters    6 年前

bool() 测试 真理价值 所以你想看看 rules for Truth Value Testing

默认情况下,除非对象的类定义了 __bool__() 返回的方法 False 或者 __len__()

你只实现了 __len__ 故意破坏的方法 TypeError 接到电话时。但是 当它是一个实现并且没有其他选项可用于确定真值时调用它。

__bool__ is preferred over __len__ :

__伦恩 如果已定义,则调用;如果对象的结果为非零,则将其视为真。

>>> class Z:
...     def __bool__(self):
...         return True
...     def __len__(self):
...         raise TypeError
...
>>> len(Z())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __len__
TypeError
>>> bool(Z())
True

注意,它是 len() 引发的函数实现 类型错误 当没有实现 __蓝__ 钩子。没有例外的是 __蓝__