改变对象的字符串显示__str__、__repr__、__fomat__

版权声明:17602128911 https://blog.csdn.net/bus_lupe/article/details/86102829

__str__

__str__在print的时候运行

class Foo:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return '名字是%s年龄是%s' % (self.name, self.age)
f1 = Foo('egon', 18)
x = f1.__str__()
y = str(f1)
print(f1)
print(x)
print(y)
'''
名字是egon年龄是18
名字是egon年龄是18
名字是egon年龄是18
'''

__repr__在解释器里运行

class Foo:
    def __repr__(self):
        return '小猫咪'

f1 = Foo()
print(f1)
# 小猫咪

__str__和__repr__都存在的时候,会执行__str__

class Foo:
    def __str__(self):
        return '小奶狗'

    def __repr__(self):
        return '小猫咪'

f1 = Foo()
print(f1)
# 小奶狗

注意:__str__和__repr__返回的都是字符串

__format__

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __format__(self, format_spec):
        return '{0.year}{1}{0.month}{1}{0.day}'.format(self, format_spec)

d1 = Date('2019', '01', '09')

# t = '{0.year}{0.month}{0.day}'.format(d1)
# print(t)
print(format(d1, '-'))
print(format(d1, ':'))
'''
2019-01-09
2019:01:09
'''

猜你喜欢

转载自blog.csdn.net/bus_lupe/article/details/86102829