Python魔法方法(5):__repr__(cls[,*args]) 方法

Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,它们是面向对象的 Python 的一切。它们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了某一个魔法方法,那么这个方法就会在特殊的情况下自动被 Python 所调用。

功能

定义对象被 repr() 函数或互交式解释器调用时的行为,该方法一般面向程序设计者。

参数

self 表示对象本身。

返回值

必须是一个字符串,否则抛出异常。

示例:

class MyText:

    def __repr__(self) -> str:
        return 'My is repr'


sample = MyText()
# My is repr
print(sample)
# My is repr
print(repr(sample))

结果:

My is repr
My is repr

__repr__() 是 Python 类中的一个特殊方法,由 object 对象提供,由于所有类都是 object 类的子类,所以所有类都会继承该方法。

该方法主要实现 “自我描述” 功能——当直接打印类的实例化对象时,系统将会自动调用该方法,输出对象的自我描述信息,用来告诉外界对象具有的状态信息。

但是,object 类提供的 __repr__() 方法总是返回一个对象(类名 + obejct at + 内存地址),这个值并不能真正实现自我描述的功能!如下:

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age


person = Person('zk', 20)
print(person)
print(person.__repr__())

执行结果:

<__main__.Person object at 0x0000020F6A467B20>
<__main__.Person object at 0x0000020F6A467B20>

因此,如果你想在自定义类中实现 “自我描述” 的功能,那么必须重写 repr 方法:

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return 'Person类,有name和age两个属性'


person = Person('zk', 20)
print(person)
print(person.__repr__())

执行结果:

Person类,有name和age两个属性
Person类,有name和age两个属性

猜你喜欢

转载自blog.csdn.net/youzhouliu/article/details/125233550
今日推荐