简体   繁体   English

object.__str__ 和 object.__repr__ 是做什么的? 警告:它与 Class.__str__ 和 Class.__repr__ 不同

[英]What does object.__str__ and object.__repr__ do? Warning: It's not the same as Class.__str__ and Class.__repr__

class TestClass:
    def __init__(self):
        pass
    def __str__(self):
        return 'You have called __str__'
    def __repr__(self):
        return 'You have called __repr__'

a = TestClass()
print(object.__repr__(a))
print(object.__str__(a))

Output: Output:

<__main__.TestClass object at 0x7fe175c547c0>
You have called __repr__

What does those two functions do?这两个函数有什么作用?


My understanding is that calling str(a) returns a.__str__() and calling repr(a) returns a.__repr__() .我的理解是调用str(a)返回a.__str__()并调用repr(a)返回a.__repr__() print(a) also prints the string, a.__str__() since there is an implicit str(a) conversion going on. print(a)还打印字符串a.__str__()因为正在进行隐式str(a)转换。

Note that my question is not a duplicate to another popular question;请注意,我的问题与另一个热门问题不重复; see my first comment below.请参阅下面我的第一条评论。

The behaviour is COUNTERINTUITIVE;这种行为是违反直觉的; doing print(object.__str__(a)) prints the repr string instead of the str string.执行print(object.__str__(a))打印 repr 字符串而不是 str 字符串。

The object class provides default implementations for the __repr__ and __str__ methods. object class 提供了__repr____str__方法的默认实现。

  • object.__repr__ displays the type of the object and its id (the address of the object in CPython) object.__repr__显示object的类型及其id (object在CPython中的地址)

  • object.__str__(a) calls repr(a) . object.__str__(a)调用repr(a) The rationale is that if __str__ is not overriden in a class str(a) will automatically call repr(a) , using a possible override of __repr__ .基本原理是,如果__str__未在 class 中被覆盖,则str(a)将自动调用repr(a)使用可能的__repr__覆盖 More exactly, the official documentation of the Python Language Reference / Data Model / Special method names / Basic customization says:更确切地说,Python Language Reference / Data Model / Special method names / Basic customization 的官方文档说:

    object.__str__(self)

    ...The default implementation defined by the built-in type object calls object.__repr__() . ...由内置类型 object 定义的默认实现调用object.__repr__()

    ... which in turn calls the overriden __repr__ method like repr(object) would have done. ...这又会像repr(object)那样调用重写的__repr__方法。

This is exactly what happens here because you are directly calling object.__str__ while this is not expected.这正是此处发生的情况,因为您直接调用object.__str__而这不是预期的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM