zoukankan      html  css  js  c++  java
  • class类 __repr__ 与__str__

    >>> class Student(object):
    ... def __init__(self, name):
    ... self.name = name
    ... def __str__(self):
    ... return 'Student object (name: %s)' % self.name
    ...
    >>> s = Student('Michael')
    >>> s
    <__main__.Student object at 0x00000000022073C8>
    >>> print(Student('Michael'))
    Student object (name: Michael)
    >>>

    -------------------------------------------------------------------------------------------

    没有写__str __()会调用 __repr__() 方法:

    >>> class Student(object):
    ... def __init__(self, name):
    ... self.name = name
    ... def __repr__(self):
    ... return 'Student object (name: %s)' % self.name
    ...
    >>> print(Student('Michael'))
    Student object (name: Michael)
    >>> s= Student('Michael')
    >>> s
    Student object (name: Michael)
    >>>

    在cmd下运行的Python3.6.5

    说明:

    用print()打印实例调用的是__str__()方法
    不用print()打印实例调用的是__repr__()方法

    If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

    如果类定义__repr __()但不定义__str __(),那么当需要该类的实例的“informal”字符串表示时,也会使用__repr __()。

    参考:
    https://docs.python.org/3/reference/datamodel.html?highlight=__repr__#object.__repr__
    https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319098638265527beb24f7840aa97de564ccc7f20f6000
    https://www.cnblogs.com/aomi/p/7026532.html

  • 相关阅读:
    P3833 [SHOI2012]魔法树 (树链剖分模板题)
    2019 Multi-University Training Contest 4 1008K-th Closest Distance(二分+主席树)
    bzoj3631: [JLOI2014]松鼠的新家(树上差分)
    bzoj4326: NOIP2015 运输计划(二分+LCA+树上差分)
    目录
    希望是一个全新的开始
    模板
    模板
    SCUT
    模板
  • 原文地址:https://www.cnblogs.com/lighthouse/p/9640709.html
Copyright © 2011-2022 走看看