我正在尝试使类的行为像元组那样,作为元组的一个属性,因此len(instance)与len(instance.tup)相同,instance [3]将返回instance.tup [3 ]等。这是课程:
class mytup(object):
def __init__(self, a):
self.tup = tuple(a)
def __getattr__(self, nm):
f = types.MethodType(lambda self:getattr(self.tup, nm)(), self, type(self))
f.__func__.func_name = nm
setattr(self, nm, f)
return f
Run Code Online (Sandbox Code Playgroud)
我可以
mt = mytup(range(10))
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试:
In [253]: len(mt)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-253-67688b907b8a> in <module>()
----> 1 len(mt)
TypeError: object of type 'mytup' has no len()
Run Code Online (Sandbox Code Playgroud)
mt实际上确实有一个__len__,我可以称之为:
In [254]: mt.__len__
Out[254]: <bound method mytup.__len__ of <__main__.mytup object at 0x2e85150>>
In [255]: mt.__len__()
Out[255]: 10
Run Code Online (Sandbox Code Playgroud)
(我什至将其重命名为__len__)。据我所知,这看起来就像我做的一样:
def __len__(self, …
Run Code Online (Sandbox Code Playgroud) python ×1