如果要把一个类的实例变成 str,就需要实现特殊方法__str__():
不使用__str()__ 时
class Member:
def __init__(self , name , number):
self.name = name
self.number = number
# def __str__(self):
# return ('Information: name:%s,number:%d' %(self.name , self.number))
m = Member('wang', 3000)
print(m)
'''
<__main__.Member object at 0x000001897F9886A0>
'''
使用__str()__ 时:
class Member:
def __init__(self , name , number):
self.name = name
self.number = number
def __str__(self):
return ('Information: name:%s,number:%d'
%(self.name , self.number))
__repr__ = __str__
'''
__repr__ = __str__ 使用时可保证在控制台>>> m 时 任然输出
Information: name:wang,number:3000
'''
m = Member('wang', 3000)
print(m)
'''
Information: name:wang,number:3000
'''
class Manager(Member):
def __init__(self , name , number , year):
super(Manager , self).__init__(name , number)
self.year = year
def __str__(self):
return ('Information: name:%s,number:%d , year:%s'
%(self.name , self.number , str(self.year)))
M1 = Manager('bob' , 15 , 2017)
print(M1)
'''
Information: name:bob,number:15 , year:2017
'''