Py学习  »  Python

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

Hernan • 5 年前 • 1526 次点击  

请考虑以下代码:

>>> 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
 
1526 次点击  
文章 [ 1 ]  |  最新文章 5 年前