2019-01-19
阅读量:
698
如何在没有__len__的数据类型定义的对象上添加__len
根据文档,这不起作用,因为:
对于自定义类,只有在对象的类型上定义,而不是在对象的实例字典中,才能保证特殊方法的隐式调用正常工作。这种行为是以下代码引发异常的原因:
>>> class C:
... pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()
我曾经在一个没有的函数发生器上尝试过这个__len__,但我事先知道它的长度,然后,我尝试用类似的东西修补它c.__len__ = lambda: 5,但它一直说生成器对象没有长度。
def get_sections(loaded_config_file):
for module_file, config_parser in loaded_config_file.items():
for section in config_parser.sections():
yield section, module_file, config_parser






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论