小白學python之定製類_學習筆記

本文以廖雪峯的官方網站爲參考來學習python的。其學習鏈接爲廖雪峯小白學python教程

本文是學習到python的定製類。參考鏈接廖雪峯python定製類

本學習筆記僅供參考。

__str__

class Student(object):
    def __init__(self,name):
        self.name = name
    def __str__(self):
        return 'Student object (name: %s)' %self.name

print(Student('Michael'))

運行結果:

Student object (name: Michael)

__iter__


class Fib(object):
    def __init__(self):
        self.a,self.b = 0,1 #初始化兩個計數器a,b

    def __iter__(self):
        return self         #實例本身就是迭代對象,故返回自己

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b #計算下一個值
        if self.a >100000:  #退出循環的條件
            raise StopIteration()
        return self.a

for n in Fib():
    print(n)

運行結果:

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
 

筆記

Python的for循環就會不斷的調用該迭代對象的__next__()方法拿到循環的下一個值,直到遇到StopIteration退出。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章