如何在 Python 中实现一个行为类似于序列的最小类?

问题描述:

我正在寻找一个在 Python 中模拟不可变序列的类的最小示例.

I am looking for a sample minimal example of a class that mimics an immutable sequence in Python.

class MySequence()
    ...

a = MySequence()

len(a)

for i in a:
    pass

a[0]

必须实现的方法有哪些?

What are the methods that must be implemented?

如果您只想能够迭代您的序列,您只需要实现返回一个可迭代对象的 __iter__ 方法.最简单的方法是使用 yield 语句创建一个生成器.

If you just want to be able to iterate over your sequence, you just need to implement the __iter__ method returning an iterable. The easiest way to do this is to create a generator using the yield statement.

class MySequence(object):
    def __iter__(self):
        yield 1
        yield 2
        yield 3

for x in MySequence():
    print x # prints 1, then 2, then 3

然而,这不会启用诸如 MySequence()[1] 之类的东西.为此,您需要实现 __getitem__ 方法,并且可能还应该实现 __len__ .

However, this will not enable things like MySequence()[1]. For that you need to implement the __getitem__ method, and should probably implement __len__ as well.

class MySequence(object):
    def __len__(self):
        return 3

    def __getitem__(self, key):
        if key == 0:
            return 1
        elif key == 1:
            return 2
        elif key == 2:
            return 3
        else:
            raise IndexError()

s = new MySequence()

for i in range(len(s)):
    print s[i] # prints 1, then 2, then 3

for x in s:
    print x # prints 1, then 2, then 3

请注意,我省略了 __iter__.只要 __getitem__ 在您尝试获取越界值时引发 IndexError,Python 就可以使用它进行迭代.(如果我想更清楚,或者想要非标准的迭代行为,我仍然可以包含 __iter__.)

Notice that I omitted __iter__. As long as __getitem__ raises an IndexError when you try to get a value that's out-of-bounds, Python can use it for iteration. (I could still include __iter__ if I wanted to be clearer, or wanted non-standard iteration behaviour.)