Python寫乙個物件,讓它自己能夠迭代

2022-07-30 18:00:16 字數 3239 閱讀 4715

仿寫range()物件,物件是可迭代的:

1

#!usr/bin/env python32#

-*- coding=utf-8 -*-34

class

myrange():5#

初始化,也叫建構函式

6def

__init__

(self,n):

7 self.i =0

8 self.n =n910

#類中核心,返回了迭代器本身;

11def

__iter__

(self):

12return

self

1314

#迭代器開始

15def

__next__

(self):

16if self.i 17 i =self.i

18 self.i += 1

19returni20

else:21

raise

stopiteration();

22print(dir(myrange(10)));

23 a = myrange(10);

24print(dir(a)); #

輸出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'i', 'n']

2526

if__name__ == "

__main__":

27 a = myrange(10)

28print("

a*****====>

", next(a)); #029

print("

next a====>

", next(a)); #130

print("

next a====>

", next(a)); #231

print("

next a====>

", next(a)); #332

print("

next a====>

", next(a)); #433

print("

next a====>

", next(a)); #534

print("

next a====>

", next(a)); #635

print("

next a====>

", next(a)); #736

print("

next a====>

", next(a)); #837

print("

next a====>

", next(a)); #938

print("

next a====>

", next(a)); #

發起raise stopiteraion()

39

上面是用next()把迭代器的所有元素乙個乙個依次列印出來的,當然也可以用for迴圈迴圈出來. for i in x: print(i),然後再用next(a)就會發起raise stopiteration()。下面用列表嘗試一下:

1

#!usr/bin/env python32#

-*- coding=utf-8 -*-34

class

myrange():5#

初始化,也叫建構函式

6def

__init__

(self,n):

7 self.i =0

8 self.n =n910

#類中核心,返回了迭代器本身;

11def

__iter__

(self):

12return

self

1314

#迭代器開始

15def

__next__

(self):

16if self.i 17 i =self.i

18 self.i += 1

19returni20

else:21

raise

stopiteration();

22print(dir(myrange(10)));

23 a = myrange(10);

24print(dir(a)); #

輸出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'i', 'n']

2526

if__name__ == "

__main__":

27 b = myrange(10)

28print(list(b)) #

全部列印出來了,後續沒有元素了

29print("

b===>next b

", next(b)) #

stopiteration.

把迭代器裡的所有元素裝到列表中後,再呼叫next()也會發起:raise stopiteraion.

自己寫乙個LIST

pragma once forward declarations templateclass clistnode templateclass clist template class clistnode void insertafter t data template void clistnode ...

自己寫乙個框架

自己寫乙個框架 單入口mvc 類 庫 屬於擴充套件 乙個好的配置檔案和讀取功能 db介面 dispather.php index.php dispather 分析controller action 根據分析controller action 動態載入 引入乙個自動載入機制 controller.ph...

自己寫乙個BaseDao

通過反射可以獲得實體的屬性和類的名字我們就可以拼接處sql語句 查詢的萬能dao public static void select object o 通過物件獲取類物件 class c o.getclass 獲取類中的屬性 field fields c.getdeclaredfields 設定許可...