Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

David Fisher
David Fisher
3,375 Points

How 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?

morse.py
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
Steven Parker
221,451 Points

I'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
David Fisher
3,375 Points

Thanks 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
Steven Parker
221,451 Points

The "__iter__" method makes objects of the Letter class iterable.
The "self.pattern" inside it was always iterable because it is a list.

David Fisher
David Fisher
3,375 Points

That 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!