python Class:面向对象高级编程 __getitem__
2018-07-20 11:14
821 查看
官网解释:
Called to implement evaluation of
对于Fibonacci数列,当我们想抽取特定位置的值看,那又该怎么做,于是就出来了__getitem__这样的函数。
int、list类型:切片(没有step)
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
f = Fib()
print f[0:4]
print f[9]
object.
__getitem__(self, key)
Called to implement evaluation of
self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the
__getitem__()method. If key is of an inappropriate type,
TypeErrormay be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values),
IndexErrorshould be raised. For mapping types, if key is missing (not in the container),
KeyErrorshould be raised.Note:
forloops expect that an
IndexErrorwill be raised for illegal indexes to allow proper detection of the end of the sequence.
对于Fibonacci数列,当我们想抽取特定位置的值看,那又该怎么做,于是就出来了__getitem__这样的函数。
int、list类型:切片(没有step)
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
f = Fib()
print f[0:4]
print f[9]
相关文章推荐
- 廖雪峰Python教程1轮还没学明白的(2) -- 面向对象高级编程 -- 定制类 -- 实现Fib数列的__getitem__()/切片方法
- python Class: 面向对象高级编程 __iter__ 和 next()
- python Class:面向对象高级编程 元类:metaclass
- python Class:面向对象高级编程 @property
- python Class:面向对象高级编程 __getattr__
- python Class:面向对象高级编程 __str__ / __repr__
- python Class:面向对象高级编程 @property
- python Class:面向对象高级编程 __call__& callable()
- python Class:面向对象高级编程
- python Class:面向对象高级编程 Enum(枚举)、@unique
- python Class:面向对象高级编程 元类:type
- Python 面向对象高级编程――使用__slots__
- python 2.7 : 面向对象高级编程
- 【Python】学习笔记——-8.3、面向对象高级编程:3.多重继承
- python——(面向对象高级编程)使用@property
- python第七天学习记录——面向对象高级以及socket编程
- Python 面向对象高级编程――使用@property
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- python面向对象高级编程
- Python学习系列:面向对象高级编程(-)