Python类的__str__()方法

如果要把一个类的实例变成 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)

输出结果:

你可能感兴趣的:(python)