Python中class的内置函数__str__
来源:互联网 发布:js 获取http 的状态 编辑:程序博客网 时间:2024/05/18 01:42
在python中,如果我们定义一个class:
class Friend():
def __init__(self, name):
self.name = name
if __name__ == '__main__':
friend = Friend('Liang')
print friend
那么在申明一个实例对象friend并打印其信息时,python返回的是它的存储地址
<__main__ .Friend instance at 0x7ff3596c>
到底应该怎么做才能打印出一个对象的有感内容呢?可以通过__str__函数
class Friend():
def __init__(self, name):
self.name = name
def __str__(self):
return "Friend : %s" % self.name
if __name__ == '__main__':
friend = Friend('Liang')
print friend
此时,打印出的内容为:
Friend name : Liang
class Friend():
def __init__(self, name):
self.name = name
if __name__ == '__main__':
friend = Friend('Liang')
print friend
那么在申明一个实例对象friend并打印其信息时,python返回的是它的存储地址
<__main__ .Friend instance at 0x7ff3596c>
到底应该怎么做才能打印出一个对象的有感内容呢?可以通过__str__函数
class Friend():
def __init__(self, name):
self.name = name
def __str__(self):
return "Friend : %s" % self.name
if __name__ == '__main__':
friend = Friend('Liang')
print friend
此时,打印出的内容为:
Friend name : Liang
显然的,内置函数带来了这种便利,理所当然要有所约束,那就是这个方法只能返回str,并且只能有self这一个参数,其他的,自行发挥。
原文链接:http://blog.csdn.net/r91987/article/details/7214215
0 0
- Python中class的内置函数__str__
- Python中class的内置函数__str__
- Python中class的内置函数__str__
- Python -- class内置函数__str__
- python内置函数__init__及__str__的区别
- python内置函数__init__及__str__的区别
- python中__str__()函数的用法
- python内置函数__str__作用说明
- python 内置__str__作用
- python中__str__和__repr__的区别
- python中__str__, __call__方法
- python中 __str__和__repr__
- Python中__str__和__repr__
- Python中 内置函数
- python中几个内置函数的用法
- Python中内置的字典函数
- Python中列表的内置函数
- python 类的打印__str__
- Codeforces Round #324 (Div. 2) A. Olesya and Rodion
- 数据结构之栈的链式存储结构
- VS调测插件开发理解总述-Addin
- VC++ .NET 动态加载DLL,使用反射方式Invoke委托调用
- 树形数组
- Python中class的内置函数__str__
- C#高级篇(二)---LINQ、反射、线程
- 文章标题
- 使用android中的AIDL让Service与Activity通信(service回调activity)
- 【hdu4427】【zoj3662】math magic 背包+厉害的优化
- 新手学习,web编程入门(二)——语言学习入门之道
- abstract_factory
- 排序学习_冒泡排序
- 判断一个数是否为Happy数