如果要把一个类的实例变成 str,就需要实现特殊方法__str__():
不使用__str__()方法
class Student(object):
def __init__(self,id,name,age):
self.id=id
self.name=name
self.age=age
s=Student(111,"Bob",18)
print(s)
输出结果:
![]()
使用__str__()方法
class Student(object):
def __init__(self,id,name,age):
self.id=id
self.name=name
self.age=age
def __str__(self):
return "学号:{}--姓名:{}--年龄{}".format(self.id,self.name,self.age)
__repr__ = __str__
'''
__repr__ = __str__ 使用时可保证在控制台>>> print() 时 任然输出
学号:111--姓名:Bob--年龄18
'''
s=Student(111,"Bob",18)
print(s)
输出结果:
![]()
336



被折叠的 条评论
为什么被折叠?



