网站首页 > 技术文章 正文
在Python中,魔法方法(通常称为特殊方法或双下方法)是面向对象编程中的一个重要概念,它们以两个下划线 __ 开头和结尾,例如 __init__
通常,我们定义一个类,
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
我们打印一个实例化类对象
>> test = Test()
>> test
<__main__.Test object at 0x0000018D0CA6CB90>
>> print(test)
<__main__.Test object at 0x0000018D0CA6CB90>
这样看实在是不怎么友好,
我们可以使用__str__,__repr__这两个魔法方法,让显示更友好。
- __repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。
- 打印对象时首先尝试__str__,它通常应该返回一个友好的显示。 __repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,
- 实际上__str__只是覆盖了__repr__以得到更友好的用户显示。当我们想所有环境下都统一显示的话,可以重构__repr__方法
如果只有__repr__魔法方法,代码如下:
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
def __repr__(self):
return self.data
则类对象输出如下:
>> t=Test()
>> t
hello, world!
>>print(t)
hello, world!
如果同时有__str__和__repr__,代码如下:
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
def __repr__(self):
return self.data
def __str__(self):
return 'value is %s'%self.data
注意输出的不同
>> t=Test()
>> t
hello, world!
>> print(t)
value is hello, world!
更友好的写法
class Test(object):
def __init__(self,value='hello word'):
self.data=value
def __str__(self):
return self.data
__str__=__repr__
猜你喜欢
- 2025-05-03 如何在 Python 中创建一个不可变的字典 - Adam Johnson
- 2025-05-03 Python中while循环详解(python写while循环)
- 2025-05-03 详细介绍一下Python中的BeautifulSoup库的使用?
- 2025-05-03 Python 编译加速技术(python编译速度)
- 2025-05-03 Python 运算符大揭秘(python运算符代码)
- 2025-05-03 Python | range()详解(python 中 range)
- 2025-05-03 Python6大基础运算符,看完这篇之后会让你有一个彻底认识
- 2025-05-03 Python 3 中 “1000000000000000 in range(1000000000000001)” 为何快
- 2025-05-03 「Python编程规范」语句分隔符号(python用什么作为分隔符)
- 2025-05-03 Python中的虚拟环境和包管理(python虚拟环境conda)
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)