目的: 觀察實作__str__, __repr__的效果
實作前:
#!/usr/bin/python
class A:
def __init__(self, x, y):
self.x = x
self.y = y
a = A(5, 6)
print a
print "%r" % a
print "{0!r}".format(a)
print str(a)
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance="">
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance="">
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance="">
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance="">
實作後:
#!/usr/bin/python
class A:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'This is A __str__'
def __repr__(self):
return '<A __repr__>'
a = A(5, 6)
print a
print "%r" % a
print "{0!r}".format(a)
print "{0!s}".format(a)
print str(a)
This is A __str__
<A __repr__>
<A __repr__>
This is A __str__
This is A __str__
沒有留言:
張貼留言