【python】类内置函数

xiaoxiao2021-02-28  91

python类内置函数:

# __init__:类构造函数 # __slots__:允许类添加的属性名 # __str__:类似java类toString方法 # __repr__:引用对象toString # __iter__:for...in,类似java.List的iterator,以StopIteration()结束循环 # __getitem__:类似java.ArrayList的下标索引或者java.Map的key索引,但需要支持切片,步长递进 # __setitem__:与__getitem__对应 # __delitem__:与__getitem__对应 # __getattr__:返回对象指定属性值, __setattr__,...

1、__getitem__

TODO:尝试动态变长的list,具有list的下标索引、切片特性,类似于下面的结果:

索引号01234索引号-5-4-3-2-1值01234 那么,对上面list=[0,1,2,3,4]取值,有 list[::]=[0,1,2,3,4] list[0:30]=[0,1,2,3,4] list[1:4:0] # error

list[0:4:2]=[0,2] list[4:0:-2]=[4,2] list[0:4:-2]=[] list[4:0:2]=[]

list[-4:-2]=[1,2] list[-2:-5:-1]=[3,2,1] list[-4:-2:1]=[1,2] list[-2:-5]=[] list[-4:-2:-1]=[]

list[-5:4:2]=list[0:4:2]=[0,2] list[-5:30]=list[0:5]=[0,1,2,3,4] list[3:-1]=list[3:4]=[3] ......

实现:

class Fib(object): def __init__(self, limit=100): self.__limit = limit def __getitem__(self, item): limit = self.__limit if isinstance(item, int): # 下标索引 a, b = 0, 1 if item >= 0: if item > limit: raise AttributeError('out bound of list size') end = item+1 else: if limit+item < 0: raise AttributeError('out bound of list size') end = limit + item + 1 for i in range(end): a, b = b, a+b return a if isinstance(item, slice): start = 0 if item.start is None else item.start end = limit if item.stop is None else item.stop step = 1 if item.step is None else item.step if step == 0: raise AttributeError('slice step cannot be zero') L = [] if (start>=0 and end<0) or (end>=0 and start<0): start = start if start>0 else (0 if start<-limit else limit+start) end = end if end>0 else (0 if end<-limit else limit+end) if start >= 0 and end >= 0: if start > end and step < 0: order = 1 # reverse step = -step start, end = end + step, start + step elif start < end and step > 0: order = 0 else: # start < end and step < 0 return L elif start < 0 and end < 0: if start < end and step > 0: order = 0 start, end = limit+start+1, limit+end+1 elif start > end and step < 0: order = 1 step = -step start, end = limit + end + step, limit + start + step else: return L else: print "1.???" return temp = start end = limit if end>limit else end a, b = 0, 1 for i in range(end): a, b = b, a+b if i >= temp: L.append(a) temp = temp + step if order == 0: return L else: L.reverse() return L

python类内置函数很多,后面学到了再往这里添吧。

转载请注明原文地址: https://www.6miu.com/read-70549.html

最新回复(0)