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

Morse Code Printer Question

Can anyone explain to me why this code doesn't work? I discovered that I should not have been passing 'pattern' to the str function, but I'm not sure why. Thank you!

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

    def __str__(self, pattern):
        dajoiner = "-"
        result = []
        for i in pattern:
            if i == ".":
                result.append("dot")
            if i == "_":
                result.append("dash")
        return dajoiner.join(result)

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

2 Answers

Steven Parker
Steven Parker
243,658 Points

The pattern is already stored in the object as "self.pattern". So the __str__ function should act on that one and not take a new one as an argument.

I had the same problem, I removed pattern from the argument and it worked!

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

    def __str__(self):
        new_pattern = []
        for x in self.pattern:
            if x == ".":
                new_pattern.append("dot")
            elif x == "_":
                new_pattern.append("dash")

        return "-".join(new_pattern)

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