__len__():当使用len(A)该对象时调用该方法,当没有该方法是会报错,且返回数据不为整数也会报错
- class A(object):
- def __init__(self,num):
- self.num = num
- self.start_num = -1
- def __len__(self):
- '''''
- @summary: 当使用len(Test)该对象时调用该方法,当没有该方法是会报错,且返回数据不为整数也会报错
- '''
- print "__len__"
- return self.num - self.start_num - 1
- if __name__ == "__main__":
- print len(A(10))
输出:
- __len__
- 10
__reversed__():当使用reversed函数翻转对象时调用
- class A(object):
- def __init__(self,num):
- self.num = num
- def __reversed__(self):
- '''''
- @summary: 当使用reversed函数翻转对象时调用
- '''
- ret = []
- for i in range(self.num):
- ret.append(self.num - i-1)
- return ret
- if __name__ == "__main__":
- print reversed(A(10))
输出:
- [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
__contains__():当使用in,not in 对象的时候 调用(not in 是在in完成后再取反,实际上还是in操作)
- class A(object):
- def __init__(self,num):
- self.num = num
- def __contains__(self, item):
- '''''
- @summary:当使用in,not in 对象的时候 ,not in 是在in完成后再取反,实际上还是in操作
- '''
- print "__contains__:%s is in?"%item
- if item < self.num and item >= 0:
- return True
- return False
- if __name__ == "__main__":
- if 3 in A(10):print "True"
- else:print False
- if 3 not in A(10):print "True"
- else:print False
输出:
- __contains__:3 is in?
- True
- __contains__:3 is in?
- False