__repr__
对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串__str__
对应str(object)这个函数,返回一个字符串对象,适合用于print输出__bytes__
对应bytes(object)这个函数,返回bytes对象
class B: def __init__(self,name): self.name = name def __repr__(self): return 'call __repr__ name is {0}'.format(self.name) def __str__(self): return 'call __str__ name is {0}'.format(self.name) def __bytes__(self): return 'call __bytes__ name is {0}'.format(self.name).encode('utf-8')
b = B('zhaochj')
1 b 2 call __repr__ name is zhaochj
1 print(b) 2 call __str__ name is zhaochj
1 str(b) 2 'call __str__ name is zhaochj'
1 bytes(b) 2 b'call __bytes__ name is zhaochj'