python - 让一个类充当元组

标签 python

我试图让一个类在各个方面都像元组那样作为类的一个属性,所以 len(instance) 将与 len(instance.tup) 相同,instance[3] 将返回实例。 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

我可以

mt = mytup(range(10))

但如果我尝试:

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()

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

(我什至将其重命名为 __len__)。据我所知,这看起来应该和我做的一样:

def __len__(self, *a):
    return self.tup.__len__(*a)

但是 python 不允许我使用 len(mt)(或 mt[2] 或 mt [1:5])。

最佳答案

新式类查找“特殊方法”——那些以两个下划线字符开头和结尾的方法——在实例的上而不是涉及的实例上,所以当len() 被调用时它会尝试调用 typeof(mt).__len__()。所以做你想做的事情的正确方法是使用 Abstract Base Classes for Containers 之一在 collections 模块中(自 Python 3.3 起)

import collections.abc

class MyTuple(collections.abc.Sequence):
    def __init__(self, a):
        self.tup = tuple(a)

    def __len__(self):
        return len(self.tup)

    def __getitem__(self, index):
        return self.tup[index]

mt = MyTuple(range(10))
print(len(mt))  # -> 10
print(mt[4])  # -> 4

关于python - 让一个类充当元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163192/

相关文章:

python - 在 Pandas DataFrame 中查找值的更快方法?

python - Python : IndexError: index 7 is out of bounds for axis 1 with size 7

python - 如何更新 python 列表中的值?

python - 用python进行傅立叶变换

python - sudo 找不到新的 python 版本

具有默认参数的 Python 类构造函数

python - Python中获取下一个字符代码加1

Python select() 在 forkpty() 之后不等待终端输入

python - 在python中按列连接两个大文件

python - 在 Pandas 数据框中插入缺失的类别和日期