您的位置:首页 > 编程语言 > Python开发

python学习——特殊方法__str__的用法

2017-10-01 22:57 453 查看
类中的str方法是在打印类的实例对象时,调用该方法,一般返回一个字符串。例如:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: