python中_str_使用方法
2017-07-26 23:34
190 查看
定义__str__()方法:
总结:在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法。当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据。
class Car: def __init__(self, newWheelNum, newColor): self.wheelNum = newWheelNum self.color = newColor def __str__(self): msg = "嘿。。。我的颜色是" + self.color + "我有" + int(self.wheelNum) + "个轮胎..." return msg def move(self): print('车在跑,目标:夏威夷') BMW = Car(4, "白色") print(BMW) |
总结:在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法。当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据。
相关文章推荐
- Python3基础 __str__ print一个类的实例对象的时候 使用的魔法方法
- Python--str与repr以及eval的使用方法
- python:使用静态方法,__str__函数
- Python字符串str的方法使用
- 关于python -os.mkdir(str)方法的使用记录
- python-str方法使用
- Python使用re实现str.strip()方法,去除首尾的空格
- p4.pm p4python p4perl p4api 的使用方法
- 升级Python导致Yum服务不能使用的修复方法
- PYTHON 模块中使用了traceback 模块报错时的解决方法
- Python strip lstrip rstrip使用方法(字符串处理空格)
- python基础31[list+tuple+set+dict+str+file的成员方法]
- Python strip lstrip rstrip使用方法
- Python 中__init__.py的使用(通过包调用方法)
- Python __getattr__与__setattr__使用方法
- Python中使用中文的方法
- 使用python获取本地时区的几种方法
- Python源代码中使用中文的方法
- Python strip lstrip rstrip使用方法
- python的str,unicode对象的encode和decode方法(转)