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

  • 相关阅读:
    第一本书 第七章(课后题)
    java基础小测试
    随笔1
    随笔
    日记 晴 2017.7.30
    自我介绍
    与或非逻辑运算符 与或非位运算符
    日记1 天气阴 阵雨
    归并排序的两个版本实现代码
    Winedt打开tex文件报错error reading的解决方案
  • 原文地址:https://www.cnblogs.com/lighthouse/p/9640709.html
Copyright © 2011-2022 走看看