Python自定义的类,为什么需要重写__str__
来源:互联网 发布:淘宝分享有礼怎么设置 编辑:程序博客网 时间:2024/05/20 06:07
首先,自定义的类在不继承任何基类的情况下,也具有__str__属性:
class RoundFloatManual(object):... def __init__(self, val):... assert isinstance(val, float), \... "Value must be a float!"... self.value = round(val, 2)
rfm = RoundFloatManual(5.590464)
dir(rfm)
返回:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']
__str__
是 Python 類中的特殊方法,他的回傳值就是使用 str(x)
所得到的值, 而 print(x)
其實就等於是 print(str(x))
.其實再講細一點,當我們呼叫 str(x)
的時候其實是呼叫x.__str__()
也就是說我們可以這樣想像:
print(x)
=== print(str(x))
=== print(x.__str__())
一般我們 自定義的類,
__str__
方法的回傳值是默認的字串,比如說: <__main__.Mylist object at 0x0071A470>
用以說明 namespace, class name 和位置.如果要改變__str__
的回傳值,我們必須要覆寫他.
参考:https://segmentfault.com/q/1010000005110206
- Python自定义的类,为什么需要重写__str__
- python 类的打印__str__
- 自定义View中为什么需要重写onMeasure()方法?
- 自定义ViewGroup需要重写的方法
- Python中class的内置函数__str__
- Python中class的内置函数__str__
- Python中class的内置函数__str__
- python __repr__和__str__ 的区别
- python 的特殊方法 __str__和__repr__
- python 的特殊方法 __str__和__repr__
- python中__str__和__repr__的区别
- python中__str__()函数的用法
- 如果要把一个类的实例变成 str,就需要实现特殊方法__str__():
- 重写equal()为什么需要重写hashCode方法
- python笔记: 类中的__str__ 函数
- 使用HashSet 存储自定义对象,为什么需要重写hashCode()和equals()?
- 自定义对象需要重写hashcode
- HashMap中如果key是自定义的类,为什么重写hashcode()和equals()
- 组件与组件之间的通信以及vue2.0中的变化、示例
- POI生成Excel如果并发的情况报错This Style does not belong to the supplied Workbook. Are you trying to assign a s
- D3.JS之别人家的饼图动画
- Nginx Location配置总结
- 一小时搞明白注解处理器(Annotation Processor Tool)
- Python自定义的类,为什么需要重写__str__
- centos系统下安装daemontools详细指南
- 最大子段和
- 字符串Hash的原理与应用
- iOS 创建单例
- 16-12.7随笔
- 移动设备safari不支持jquery的live绑定的解决办法
- HDOJ 1856 More is better (并查集)
- 安卓build variant ----Gradle for Android( 构建变体 )