saeley7
saeley7

Reputation: 43

How to get a class to print out multiple parameters (__str__ function question)

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) 

Upvotes: 4

Views: 850

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 52049

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

Upvotes: 3

Related Questions