4

I'm creating a class that prints out its contents using the str() function. However, I can only seem to be able to get it to print out one of the parameters? When I ask it to return self.num as well as self.word it throws an error.

Would anyone be able to help me on this?

class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        return self.word, self.num

a = Test('Word', '10')
print(a) 
3
  • 1
    __str__ must return a str; it cannot return a tuple. You'll have to create a string of them first. Commented May 31, 2020 at 18:57
  • Do you know how to format one string of several variables? Commented May 31, 2020 at 19:04
  • Sorry I don't understand, I don't know how to format one string of several variables Commented May 31, 2020 at 19:05

1 Answer 1

3

The __str__ method is expected to return a single string. To show several variables, concatenate (via + if they are strings) or format them (via f-string literals, format string templates, or printf %-formatting) into a single string.

class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        # f-string literal - ``{...}`` are replacement fields
        return f'{self.word} => {self.num}'

a = Test('Word', '10')
print(a)  # Word => 10
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that works! I'm not sure I totally understand it (I don't know what concatenate means) but I'm still a beginner and I can look into it. Thanks for your help!
To concatenate means to create a new string by attaching two existing strings to each other. For example, your could define __str__ to return self.word + self.num. Note that you generally cannot concatenate other types to a string, for example 'Word' + 10 will not work (note that the 10 is not quoted - it is an integer number).
@saeley7 Glad to have helped. Please consider to upvote and/or accept this answer if it solves your problem. See What should I do when someone answers my question? for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.