zoukankan      html  css  js  c++  java
  • python中__str__与__repr__的区别

    str__和__repr

    __str__和__repr__都是python的内置方法,都用与将对象的属性转化成人类容易识别的信息,他们有什么区别呢

    来看一段代码

    from math import hypot
    
    
    class Vector:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def __str__(self):
            return 'Vector(%r,%r)' % (self.x, self.y)
    
        def __abs__(self):
            return hypot(self.x, self.y)
    
        def __bool__(self):
            return bool(abs(self))
    
        def __add__(self, other):
            x = self.x + other.x
            y = self.y + other.y
            return Vector(x,y)
    
        def __mul__(self, scalar):
            """相乘时调用__mul__方法"""
            return Vector(self.x * scalar, self.y * scalar)
    
    

    在控制台进行如下输入 ```python from cheapter_1.vector import Vector v1=Vector(3,4) v1 print(v1) Vector(3,4)
    
    <br>
    把__str__换成__repr__
    ```python
        def __repr__(self):
            return 'Vector(%r,%r)' % (self.x, self.y)
    
    

    在控制台重复上述操作 ```python from cheapter_1.vector import Vector v1 = Vector(3,4) v1 Vector(3,4) print(v1) Vector(3,4) ```
    同时定义__str__和__repr__
        def __str__(self):
            return "in __str__"
    
        def __repr__(self):
            return 'Vector(%r,%r)' % (self.x, self.y)
    

    在控制台进行以下操作 ```python from cheapter_1.vector import Vector v1=Vector(3,4) v1 Vector(3,4) print(v1) in __str__
    
    <br>
    ## 小结
    __str__和__repr__的区别主要有以下几点
    - __str__是面向用户的,而__repr__面向程序员去找
    - <b><font color='red'>打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),如果没有就尝试__repr__,都没有会输出原始对象形式</font></b>
    - <b><font color='red'>交互环境输出对象时会调用__repr__</font></b>
    
    
    <br>
    更多关于__str__与__repr__的区别:<a href='https://stackoverflow.com/questions/1436703/difference-between-str-and-repr'>Difference between __str__ and __repr__?</a>
    
    本文部分代码来源:fluent python by Luciano Ramalho(O'Reilly).Copyright 2015 Luciano Ramalho,978-1-491-94600-8
  • 相关阅读:
    uni-app 发起请求,Toast 消息提示 ,跳转页面
    uView初识
    uni-app初识
    docker目录 /var/lib/docker/containers 日志清理
    Linux中使用pigz工具更快的压缩和解压文件
    docker 修改默认网段
    LayaAir提示:版本不匹配!全局tsc(2.7.2)!=VS Code的语言服务(2.1.5)。可能出现不一致的编译错误
    C++ 格式化 浮点为字符串
    安装 ta-lib
    编译 python 代码
  • 原文地址:https://www.cnblogs.com/zzliu/p/10787606.html
Copyright © 2011-2022 走看看