gpt4 book ai didi

python - __repr__ 与代表

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:57 25 4
gpt4 key购买 nike

这两种方法有区别吗?

例如,

from datetime import date
today = date(2012, 10, 13)
repr(today)
'datetime.date(2012, 10, 13);

today.__repr__()
'datetime.date(2012, 10, 13)'

他们似乎做同样的事情,但为什么有人想要使用后者而不是常规的 repr?

最佳答案

__repr__ method用于实现 repr() 的自定义结果。它由 repr()str() 使用(如果未定义 __str__)。你不应该明确地调用 __repr__

区别在于 repr() 强制将字符串作为返回类型,并且 repr() 在类对象上查找 __repr__,而不是实例本身:

>>>> class C(object):
.... def __repr__(self):
.... return 1 # invalid non-string value
....
>>>> c = C()
>>>> c.__repr__() # works
1
>>>> repr(c) # enforces the rule
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>> c # calls repr() implicitly
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>> str(c) # also uses __repr__
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __str__ returned non-str (type 'int')
>>>> c.__repr__ = lambda: "a"
>>>> c.__repr__() # lookup on instance
'a'
>>>> repr(c) # old method from the class
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>>

关于python - __repr__ 与代表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12877619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com