__str__ and __repr__

__str__with__repr__

One,__str__

  • When printing trigger
class Foo:
    pass

obj = Foo()
print(obj)
<__main__.Foo object at 0x10d2b8f98>
dic = {'a': 1}  # d = dict({'x':1})
print(dic)
{'a': 1}

dic and obj is an instance of the object, but obj is printed memory address, and dic printing is useful information, it is clear that the printing is very good dic

class Foo:
    def __init__(self, name, age):
        """对象实例化的时候自动触发"""
        self.name = name
        self.age = age

    def __str__(self):
        print('打印的时候自动触发,但是其实不需要print即可打印')
        return f'{self.name}:{self.age}'  # 如果不返回字符串类型,则会报错


obj = Foo('nick', 18)
print(obj)  # obj.__str__() # 打印的时候就是在打印返回值
打印的时候自动触发,但是其实不需要print即可打印
nick:18
obj2 = Foo('tank', 30)
print(obj2)
打印的时候自动触发,但是其实不需要print即可打印
tank:30

two,__repr__

  • str function or print function --->obj.__str__()
  • repr or interactive interpreter --->obj.__repr__()
  • If __str__not defined, then it will use __repr__to replace the output
  • Note: The return value maybe method must be a string, or an exception is thrown
class School:
    def __init__(self, name, addr, type):
        self.name = name
        self.addr = addr
        self.type = type

    def __repr__(self):
        return 'School(%s,%s)' % (self.name, self.addr)

    def __str__(self):
        return '(%s,%s)' % (self.name, self.addr)


s1 = School('oldboy1', '北京', '私立')
print('from repr: ', repr(s1))
from repr:  School(oldboy1,北京)
print('from str: ', str(s1))
from str:  (oldboy1,北京)
print(s1)
(oldboy1,北京)
s1  # jupyter属于交互式
School(oldboy1,北京)

Guess you like

Origin www.cnblogs.com/Dr-wei/p/11851497.html