Python中的 __str__方法

类中的str方法是在打印类的实例对象时,__str__是被print函数调用的,调用该方法,一般返回一个字符串。例如:

class Rectangle():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __str__(self):
        return 'this is a str'
rect = Rectangle(3,4)
print(rect)
  • 得到结果:
this is a str
  •  

也就是说当打印一个类的实例对象时,会自动调用str方法,并返回回来一个字符串。

那么,如果返回的不是一个字符串,会出现什么结果呢?

class Rectangle():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __str__(self):
        return (self.a) * (self.b)
rect = Rectangle(3,4)
print(rect)
  •  

结果实际会报错:

TypeError: __str__ returned non-string (type int)
  •  

str返回的不是一个字符串类型,是一个整形,因此会报错。 
此时,把(self.a) * (self.b)改成str((self.a) * (self.b))就可以了。

class Rectangle():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __str__(self):
        return str(self.a) * (self.b))
rect = Rectangle(3,4)
print(rect)
  •  

得到:

12

猜你喜欢

转载自blog.csdn.net/Panda996/article/details/82495393