你想改变对象实例的打印或显示输出,让它们更具有可读性:
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