• 给类或者类的对象添加打印内容 def __repr__(self)


    通常情况下 打印一个类或者类的对象 会显示 xx.xx object at 0xaaaaabbbbbbb  只会告诉你这个对象或者类 储存在某个内存中,这是因为你的类没有实现相关的打印功能

    print (classA)
    
    # [<sort.detection.Detection object at 0x7fdcfd0734a8>, <sort.detection.Detection object at 0x7fdcfdf661d0>]
    或者
    # <__main__.Foobar instance at 0x7ff2a18c>

    类可以通过定义 __repr__() 方法控制这里函数为它的实例返回的内容。

    class Test:
     def __init__(self, a, b):
     self.a = a
     self.b = b
    
     def __repr__(self):
     return"<Test a:%s b:%s>" % (self.a, self.b)
    
     def __str__(self):
     return"From str method of Test: a is %s, b is %s" % (self.a, self.b)

    测试

    >>> t = Test(123, 456)
    >>> t
    <Test a:123 b:456>
    >>> print repr(t)
    <Test a:123 b:456>
    >>> print t
    From str method of Test: a is 123, b is 456
    >>> print str(t)
    From str method of Test: a is 123, b is 456

    __str__ 方法没有定义,print t ( 或者 print str(t) ) 将使用 __repr__的结果

    如果未定义 __repr__ 方法,则默认使用默认值,这与这里相当。

  • 相关阅读:
    大概了解了flexbox
    JS基础知识
    bugzilla_firefox
    Redis的五种数据类型
    Redis交互编程语言及客户端
    为什么要用Thrift
    知识产权代理行业公司竞争分析
    @Resource和@Autowired的区别
    Maven 3.3全局配置
    Aspose for Maven 使用
  • 原文地址:https://www.cnblogs.com/clemente/p/11237456.html
Copyright © 2020-2023  润新知