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 trial

Python

Smith Thapa
Smith Thapa
7,023 Points

Didn't get the right string output !

Question: Let's use str to turn Python code into Morse code! OK, not really, but we can turn class instances into a representation of their Morse code counterparts. I want you to add a str method to the Letter class that loops through the pattern attribute of an instance and prints out "dot" for every "." and "dash" for every "". Join them with a hyphen. I've included an S class as an example (I'll generate the others when I test your code) and it's __str_ output should be "dot-dot-dot".

morse.py
class Letter:
    hyphen_code=[]

    def __init__(self, pattern=None):
        self.pattern = pattern

    def __str__(self):
        for x in self.pattern:
            if x ==".":
                self.hyphen_code.append("dot")
            elif x=="_":
                self.hyphen_code.append("dash")
        return "-".join(self.hyphen_code)



class S(Letter):
    def __init__(self):
        pattern = ['.', '.', '.']
        super().__init__(pattern)

1 Answer

Steven Parker
Steven Parker
231,007 Points

Try using a local variable instead of a class attribute.

You don't nee to hyphen_code to be a class attribute (which would retain it's value between uses), so just make it be a local variable to the str method. Move the initialization into the method itself, and then remove the "self." prefix from each reference.