__getitem__方法的使用

在Python类中实现了__getitem__方法可以实现索引与切片的使用:

class F:
    ranks = [str(n) for n in range(2, 11)]

    def __init__(self):
        self._cards = [(rank) for rank in self.ranks]

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

    def __getitem__(self, position):
        return self._cards[position]

f = F()
print(f[3])
_slice = slice(2, 8, 2)
print(f[_slice])

输出:

5
['4', '6', '8']

还可以实现迭代和反向迭代:

class F:
    ranks = [str(n) for n in range(2, 11)]

    def __init__(self):
        self._cards = [(rank) for rank in self.ranks]

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

    def __getitem__(self, position):
        return self._cards[position]

f = F()
for item in f:
    print(item)

输出:

2
3
4
5
6
7
8
9
10

反向迭代:

class F:
    ranks = [str(n) for n in range(2, 11)]

    def __init__(self):
        self._cards = [(rank) for rank in self.ranks]

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

    def __getitem__(self, position):
        return self._cards[position]

f = F()
for item in reversed(f):
    print(item)

输出:

10
9
8
7
6
5
4
3
2

你可能感兴趣的:(python学习)