Iterator แบบกำหนดเอง

Object-Oriented Programming ใน Python ระดับกลาง

Jake Roach

Data Engineer

Iterator

คลาสที่ช่วยให้สามารถวนผ่านกลุ่มของออบเจ็กต์หรือสตรีมข้อมูล และคืนค่าทีละรายการ

  • คล้ายกับ list และ tuple แต่ทำงานต่างกัน
  • นำทาง, แปลง, สร้างข้อมูล
  • วนลูปด้วย for
  • ฟังก์ชัน next()

$$

Iterator protocol...

# Collection
chuck = NameIterator("Charles Carmicheal")
for letter in chuck:
    print(letter)
C
h
u
...
# Data stream
fun_game = DiceGame(rolls=3)
next(fun_game)  # ... and so on
4
Object-Oriented Programming ใน Python ระดับกลาง

Iterator protocol

__iter__()

  • คืนค่า iterator ในที่นี้คือการอ้างอิงถึงตัวเอง
  • ... return self

$$

__next__()

  • คืนค่าถัดไปจากกลุ่มข้อมูลหรือสตรีมข้อมูล
  • ดำเนินการวนซ้ำ แปลง และสร้างข้อมูล

$$

ต้องกำหนดทั้ง __iter__() และ __next__() เพื่อให้คลาสถูกถือว่าเป็น iterator!

Object-Oriented Programming ใน Python ระดับกลาง

ตัวอย่าง iterator

class CoinFlips:
    def __init__(self, number_of_flips):
        self.number_of_flips = number_of_flips  # Store the total number of flips
        self.counter = 0

    def __iter__(self):
        return self  # Return a reference of the iterator

    # Flip the next coin, return the output
    def __next__(self):
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])
Object-Oriented Programming ใน Python ระดับกลาง

การใช้งาน iterator

three_flips = CoinFlips(3)

# Flip the coin three times
next(three_flips)
next(three_flips)
next(three_flips)
H
H
T
Object-Oriented Programming ใน Python ระดับกลาง

การวนลูปผ่าน iterator

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
T
H
T
None
None
None
...
Object-Oriented Programming ใน Python ระดับกลาง

StopIteration

...
    def __next__(self):
        # Only do this if the coin hasn't been flipped "number_of_flips" times
        if self.counter < self.number_of_flips:
            self.counter += 1
            return random.choice(["H", "T"])

        else:  # Otherwise, stop execution with StopIteration
            raise StopIteration
  • บอกจุดสิ้นสุดของกลุ่มข้อมูล/สตรีมข้อมูล
  • ป้องกันลูปไม่สิ้นสุด
  • จัดการได้ง่าย
Object-Oriented Programming ใน Python ระดับกลาง

การวนลูปผ่าน iterator

three_flips = CoinFlips(3)

# Now, try to loop through every element of the iterator
for flip in three_flips:
    print(flip)
H
T
H
Object-Oriented Programming ใน Python ระดับกลาง

การจัดการข้อยกเว้น StopIteration

while True:
    try:
        next(three_flips)  # Pull the next element of three_flips

    # Catch a stop iteration exception
    except StopIteration:
        print("Completed all coin flips!")
        break
H
H
H
Completed all coin flips!
Object-Oriented Programming ใน Python ระดับกลาง

มาฝึกกันเถอะ!

Object-Oriented Programming ใน Python ระดับกลาง

Preparing Video For Download...