用inheritan编写repr函数的正确方法

2024-05-29 09:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试OOP python,但我不确定__repr__函数继承。因为父类函数如下所示:

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

我想知道是否最好使用一种通用的方法(也可以适用于儿童课程),如以下方法:

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

或者在每个类中重写函数是一个好的实践。

另外,请忽略编码部分,因为我要把它留下。


Tags: ofthe方法函数nameselfformatreturn
2条回答

是的--这不仅仅是“好”,而且在几乎每个项目和类层次结构中都更实际。

实际上,这几乎是一个完美的“教科书示例”,说明何时使用类继承,只需重用超类中的代码。

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

object.__repr__(self)

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

这意味着__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))

那么在为__init__添加参数时,绝对应该重写__repr__

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))

但是如果超类的__repr__仍然准确地描述了“子类,那么__repr__没有点重载:

class B(A):
     pass

然而,使用self.__class__.__name__而不是硬编码类名总是一个不错的选择,以防您或其他人对其进行子类化。

相关问题 更多 >

    热门问题