zoukankan      html  css  js  c++  java
  • 改变对象的字符串提示

    你想改变对象实例的打印或显示输出,让它们更具有可读性:
    
    class Pair:
      def __init__(self, x, y):
         self.x = x
         self.y = y
      # def __repr__(self):
      #   return 'Pair({0.x!r}, {0.y!r})'.format(self)
      # def __str__(self):
      #   return '({0.x!s}, {0.y!s})'.format(self)
    p=Pair('a','b')
    print p
    print type(p)
    print dir(p)
    
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a5.py
    <__main__.Pair instance at 0x0039BDF0>
    <type 'instance'>
    ['__doc__', '__init__', '__module__', 'x', 'y']
    
    
    
    class Pair:
      def __init__(self, x, y):
         self.x = x
         self.y = y
      def __repr__(self):
        return 'Pair({0.x!r}, {0.y!r})'.format(self)
      # def __str__(self):
      #   return '({0.x!s}, {0.y!s})'.format(self)
    p=Pair('a','b')
    print p
    print type(p)
    print dir(p)
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a5.py
    Pair('a', 'b')
    <type 'instance'>
    ['__doc__', '__init__', '__module__', '__repr__', 'x', 'y']
    
    
    
    
    
    class Pair:
      def __init__(self, x, y):
         self.x = x
         self.y = y
      def __repr__(self):
        return 'Pair({0.x!r}, {0.y!r})'.format(self)
      def __str__(self):
        return '({0.x!s}, {0.y!s})'.format(self)
    p=Pair('a','b')
    print p
    print type(p)
    print dir(p)
    
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a5.py
    (a, b)
    <type 'instance'>
    ['__doc__', '__init__', '__module__', '__repr__', '__str__', 'x', 'y']
    
    Process finished with exit code 0

  • 相关阅读:
    Redis源码分析(二十一)--- anet网络通信的封装
    leetcode 总结part1
    leetcode String to Integer (atoi)
    leetcode 165. Compare Version Numbers
    leetcode 189. Rotate Array
    leetcode 168. Excel Sheet Column Title
    leetcode 155. Min Stack
    leetcode 228. Summary Ranges
    leetcode 204. Count Primes
    leetcode 6. ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349459.html
Copyright © 2011-2022 走看看