python中的in

in有相当多的用处,平常用到最多in的地方可能就是for循环中了,比如:
for i  in range(10):
    print(i)
此处的in就是i在0到10(不包含10)这个范围内了。
稍微探究一下range这个函数,help(range)一下,看python说了些什么?
Return an object that produces a sequence of integers from start(inclusive) to stop(exclusive)
by step. range(i,j) produces i , i+1,i+2,.... , j-1. start defaults to 0,and stop is omitted! range(4) produces 0,1,2,3.
These are exactly the valid indices for a list of 4 elements. When step is given,it specifies the increment (or decrement).
以上,说的非常明白,其实range返还回来即是一个列表的索引,这就意味着in同样能对列表进行同样的操作,判断元素是否在列表中,
1 in range(10) 会返还 True 
1 in [0,1,2,3,4,5,6,7,8,9] 同样的道理也是返还 True 
那么in到底能操作什么类型的对象呐?
这是我看到对in的理解很棒的作者
作者:知乎用户
链接:https://www.zhihu.com/question/24868112/answer/83471042
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

in 关键字实现了一套python中的遍历协议.
  • 协议A: __iter__ + next
循环时, 程序先使用__iter__ (相当于iter(instance))获取具有next方法的对象, 然后通过其返回的对象, 不断调用其next方法, 直到StopIteration错误抛出.

class A:
    def __iter__(self):
        self.limit = 4
        self.times = 0
        self.init = 1
        return self

    def next(self):
        if self.times >= self.limit:
            raise StopIteration()
        else:
            x = self.init
            self.times += 1
            self.init += 1
            return x

print 'A>>>>>>'for x in A():
    print x
打印结果:
A>>>>>>
1
2
3
4
  • 协议B: __getitem__ + __len__
循环时, 程序先调用__len__ (相当于len(instance))方法获取长度, 然后循环使用 __getitem__(index) (相当于instance[index])获取元素, index in range(len(instance))

class B:

    def __init__(self):
        self._list = [5, 6, 7, 8]

    def __getitem__(self, slice):
        return self._list[slice]

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

print 'B>>>>>>'for x in B():
    print x
打印结果:
B>>>>>>
5
6
7
8
  • 协议C: yield关键字
def C():
    for x in range(9, 13):
        yield x

print 'C>>>>>>'for x in C():
    print x
打印结果:
C>>>>>>
9
10
11
12
从上边可以看出, ABC三种方式都可以实现in的循环, 对于A和B, 如果一个类把这两个方案都实现了怎么办?
class D(A, B):
    passprint 'D>>>>>>'for x in D():
    print x
打印结果:
D>>>>>>
1
2
3
4
可见, in优先使用的是A计划.
确实学习到了!
那么我们探究一下到底是这么一回事吗?首先help(list)和help(range)我们都会看到都有内置的Magic Method __iter__和__len__

以上,我们就知道什么时候能够用in,以及如何在自己定义的对象中用到in


你可能感兴趣的:(python)