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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值