TypeError: __str__ returned non-string (type NoneType) in output

930 Views Asked by At
class Point4D(object):
    def __init__(self,w, x, y, z):
        self.w = w
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        print('{}, {}, {}, {}'.format(self.w, self.x, self.y, self.z))

my_4d_point = Point4D(1, 2, 3, 1)
print(my_4d_point) 

I get the output 1 2 3 1 , but i keep getting the error TypeError: __str__ returned non-string (type NoneType) in line 12. Why?

4

There are 4 best solutions below

0
On

Use return. The error is because you print, but return nothing.

def __str__(self):
        return('{}, {}, {}, {}'.format(self.w, self.x, self.y, self.z))
0
On

you have to use the return statement instead of print because the __str__ function is supposed to return a string

class Point4D():
    def __init__(self,w, x, y, z):
        self.w = w
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return('{}, {}, {}, {}'.format(self.w, self.x, self.y, self.z))

my_4d_point = Point4D(1, 2, 3, 1)
print(my_4d_point) 

output:

1, 2, 3, 1
0
On

__str__ is supposed to return a string. Your function currently returns None. Printing a string is not returning the string.

You're almost there. Change it to the following:

    def __str__(self):
        return '{}, {}, {}, {}'.format(self.w, self.x, self.y, self.z)
0
On

method _str_ should return (not print) string repesentration of object.