Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Basic Object-Oriented Python!
You have completed Basic Object-Oriented Python!
Preview
In this step, learn how to tackle iterations using your created objects.
class Candy:
def __init__(self, name, color):
self.name = name
self.color = color
def __str__(self):
return f'{self.color} {self.name}'
class CandyStore:
def __init__(self):
self.candies = []
def __iter__(self):
yield from self.candies
def add_candy(self, candy):
self.candies.append(candy)
nerds = Candy('Nerds', 'Multi')
chocolate = Candy("Hersey's Bar", 'Brown')
my_store = CandyStore()
my_store.add_candy(nerds)
my_store.add_candy(chocolate)
for candy in my_store:
print(candy)
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
This dunder method helps Python know how
to handle iterating through an instance,
0:00
like you would with while or for loops.
0:00
Right now, if we tried to
iterate through our instance,
0:03
we would get something like this.
0:06
Car object is not iterable.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up