【发布时间】:2019-01-18 23:28:22
【问题描述】:
根据文档,这不起作用,因为:
对于自定义类,特殊方法的隐式调用只有在对象类型上定义时才能保证正常工作,而不是在对象的实例字典中。这种行为是以下代码引发异常的原因:
>>> 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()https://docs.python.org/3/reference/datamodel.html#special-method-lookup
我在没有__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
我将生成器(没有长度)传递给另一个函数(然而,另一个生成器),它需要通过调用 len() 来获得可迭代长度:
def sequence_timer(sequence, info_frequency=0): i = 0 start = time.time() if_counter = start length = len(sequence) for elem in sequence: now = time.time() if now - if_counter < info_frequency: yield elem, None else: pi = ProgressInfo(now - start, float(i)/length) if_counter += info_frequency yield elem, pi i += 1https://github.com/arp2600/Etc/blob/60c5af803faecb2d14b5dd3041254ef00a5a79a9/etc.py
然后,当尝试将__len__ 属性添加到get_sections 时,出现错误:
get_sections.__len__ = lambda: calculated_length
for stuff, progress in sequence_timer( get_sections ):
section, module_file, config_parser = stuff
TypeError: object of type 'function' has no len()
【问题讨论】:
-
你有什么问题?您引用了文档中说它不会起作用的部分。如果要自定义
len(),需要定义一个类。 -
是的,这里最简单的事情就是编写一个带有
__len__的自定义类包装器,它将您需要的所有其他内容委托给生成器对象
标签: python python-3.x generator