Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDavid Fisher
3,375 PointsHow does __init__ make this class better?
I would assume that by making it better, init would remove the need for another part of the code such as the loop in str. I've played around with it and can't figure out what I could remove. So if it just produces the same answer as before, how is adding more code making it better?
class Letter:
def __init__(self, pattern=None):
self.pattern = pattern
def __iter__(self):
yield from self.pattern
def __str__(self):
symbol_list = []
for arg in self.pattern:
if arg == ".":
symbol_list.append("dot")
if arg == "_":
symbol_list.append("dash")
return "-".join(symbol_list)
class S(Letter):
def __init__(self):
pattern = ['.', '.', '.']
super().__init__(pattern)
1 Answer
Steven Parker
231,248 PointsI'm going to guess you meant to say "__iter__
" instead of "__init__
", since it was added in this challenge.
The value of defining it is so objects of this class can be iterated. For example, if you created an instance of the Letter class named "morse", then you could use it in a loop:
for element in morse:
This wouldn't be possible if the "__iter__
" method was not defined.
David Fisher
3,375 PointsDavid Fisher
3,375 PointsThanks for your response. Iām still a little confused. If iter is needed for this reason, why was I able to loop through self.pattern in the str function before it was introduced?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsThe "
__iter__
" method makes objects of the Letter class iterable.The "self.pattern" inside it was always iterable because it is a list.
David Fisher
3,375 PointsDavid Fisher
3,375 PointsThat makes sense. I think I wasn't fully grasping what an iterable really is. I did a little research and it makes more sense now. Thanks for taking the time to answer!