Python Object-Oriented Python Dice Roller Boards

Bashir Orfani
Bashir Orfani
12,495 Points

Let's make all Board instances

Let's make all Board instances iterable so we can loop through their cells attribute. Inside the Board class, define an iter method that yields the cells. If you need help, refer back to the "Emulating Builtins" video.

boards.py
class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.cells = []
        for y in range(self.height):
            for x in range(self.width):
                self.cells.append((x, y))


class TicTacToe(Board):
    def __init__(self, width=3, height=3):  # the defaults go here instead
        super().__init__(width, height)

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 24,707 Points

Which part of this are you having trouble with?

Part 1 is a question about subclassing the Board Object and calling its super().__init__() method

Part 2 is a question about implementing an __iter__() method on the new class.

Benyamin Kohanchi
PLUS
Benyamin Kohanchi
Courses Plus Student 2,273 Points

Hey Bashir, this is how you do the second part of the challenge.

Kenneth is asking you to create a method that iterates (using __ iter __) over self.cells in the Class Board. This is what the entire code should look like:

class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.cells = []    # <---- This is what we are trying to iterate over in Challenge 2 
        for y in range(self.height):
            for x in range(self.width):
                self.cells.append((x, y))

    def __iter__(self):    #<----- Second challenge asked us to define __iter__
        for cell in self.cells:
            yield cell


class TicTacToe(Board):      # <---- First challenge asked to make this class
    def __init__(self):
        super().__init__(width=3, height=3)

Basically, we defined __ iter __ and made it loop over cells....

def __iter__(self):
        for cell in self.cells:

...and then we yielded (or returned what we wanted --> without <--- ending the program) each iterable item in the list of self.cells.

yield cell

If you have any questions, comment them down below and ill try to answer them as soon as I can. Good luck!