由于某些原因,这在Python 3.8中失败了:
setattr(iter(()), '_hackkk', 'bad idea')错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-c046f8521130> in <module>
----> 1 setattr(iter(()), '_hackkk', 'bad idea')
AttributeError: 'tuple_iterator' object has no attribute '_hackkk'如何在不应该的地方附加随机数据,例如,在迭代器或生成器上?
发布于 2020-10-10 17:59:46
只能将数据附着到具有__dict__-member的对象。并不是所有的对象都有它--例如像int、float、list等内置类就没有。这是一种优化,因为否则这些类的实例将需要太多的内存-字典具有相当大的内存占用。
此外,对于普通类,可以使用__slots__,从而删除__dict__-member,并禁止向该类的对象动态添加属性。例如。
class A:
pass
setattr(A(),'b', 2)有效,但是
class B:
__slots__ = 'b'
setattr(B(),'c', 2)不起作用,因为类B没有名为c的槽,也没有__dict__。
因此,您的问题的答案是:对于某些类(如tuple_iterator),您不能。
如果确实需要,可以使用__dict__将tuple_iterator包装在类中,并将新属性附加到包装器对象:
class IterWrapper:
def __init__(self, it):
self.it=it
def __next__(self):
return next(self.it)
def __iter__(self): # for testing
return self现在:
iw=IterWrapper(iter((1,2,3)))
setattr(iw, "a", 2)
print(iw.a) # prints 2
print(list(iw)) # prints [1,2,3]具有所需的行为。
https://stackoverflow.com/questions/64291962
复制相似问题