python学习——特殊方法__str__的用法
2017-10-01 22:57
453 查看
类中的str方法是在打印类的实例对象时,调用该方法,一般返回一个字符串。例如:
得到结果:
也就是说当打印一个类的实例对象时,会自动调用str方法,并返回回来一个字符串。
那么,如果返回的不是一个字符串,会出现什么结果呢?
结果实际会报错:
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 '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
相关文章推荐
- python str.format()方法的基本用法
- python 的特殊方法 __str__和__repr__
- python 的特殊方法 __str__和__repr__
- Python学习笔记(二)——特殊方法
- python面对对象编程------4:类基本的特殊方法__str__,__repr__,__hash__,__new__,__bool__,6大比较方法
- python学习之类特殊方法定制 __add__,__iadd__,__radd__
- Python学习笔记1:数据模型和特殊方法(魔术方法)
- python 新式类学习随笔-定制类的特殊方法(1)
- Python对象特殊方法及其用法演示
- python 新式类的学习随笔-定制类的特殊方法(2)
- PHP学习:$_GET,$_POST,$_REQUEST和$_SERVER的一些用法,以及parse_str方法
- Python学习笔记1:数据模型和特殊方法(魔术方法)
- Python学习笔记(二)——特殊方法(续)
- Python特殊方法应用学习
- 【python学习笔记】Python自带特殊方法一览
- Python学习笔记——特殊方法
- python学习系列---str和int类型内置方法
- python学习(7)定制类的特殊方法
- Python学习笔记(九)——Python _init_特殊方法和模块