使用继承编写__repr__函数的正确方法

dec*_*dle 14 python oop inheritance repr

我正在尝试使用OOP python,我不确定__repr__函数继承.由于父类函数看起来像这样:

def __repr__(self):
    '''Returns representation of the object'''
    return("{}({!r})".format("Class name", self._param))
Run Code Online (Sandbox Code Playgroud)

我想知道是否更好地使用通用方法(也适用于子类),如下所示:

def __repr__(self):
    '''Returns representation of the object'''
    return("{}({!r})".format(self.__class__.__name__, self._param))
Run Code Online (Sandbox Code Playgroud)

或者如果在每个班级中覆盖该功能是一个好习惯.

另外,请忽略编码部分,因为我将它留在后面.

MSe*_*ert 10

那么__repr__在Pythons数据模型中有一个特殊的含义:

object.__repr__(self)

repr()内置函数调用以计算对象的"官方"字符串表示.如果可能的话,这应该看起来像一个有效的Python表达式,可用于重新创建具有相同值的对象(给定适当的环境).如果无法做到这一点,<...some useful description...>则应返回表单的字符串.返回值必须是字符串对象.如果类定义__repr__()但未定义__str__(),则__repr__()在需要该类的实例的"非正式"字符串表示时也使用.

这通常用于调试,因此表示信息丰富且明确是很重要的.

这意味着返回的字符串__repr__应该可用于创建另一个对象.因此__repr__,通常需要重写的东西,不是因为__class__.__name__"状态"必须在表示中捕获.

class A(object):
    def __init__(self, param):
        self._param = param

    def __repr__(self):
        '''Returns representation of the object'''
        return("{}({!r})".format(self.__class__.__name__, self._param))
Run Code Online (Sandbox Code Playgroud)

那么你绝对应该覆盖__repr__添加参数的时间__init__:

class B(A):
    def __init__(self, param1, param2):
        self._param = param1
        self._param2 = param2

    def __repr__(self):
        '''Returns representation of the object'''
        return("{}({!r})".format(self.__class__.__name__, self._param, self._param2))
Run Code Online (Sandbox Code Playgroud)

但是,如果__repr__超类仍然准确地 "描述"子类,那么就没有意义重载__repr__:

class B(A):
     pass
Run Code Online (Sandbox Code Playgroud)

但是,使用self.__class__.__name__硬编码类名称总是一个不错的选择,以防你或其他人将其子类化.

  • 您应该具备从盐的建议中重新创建对象的能力:这对某些对象非常有用,但在Pyhton的“输入”将按以下类型键入的值调用“ eval”时仍然存在用户:这是交互式使用Python语言的另一种心态。根据对象的种类,它实际上不是很实用-有时甚至是不理想的-重复生成这种方式。 (2认同)