__str__或__repr__重载时的奇怪行为

时间:2019-06-26 19:01:29

标签: python-3.x string methods overloading

class MyList:
    def __init__(self, start=[]):
        print('__init__ method')
        self.list = list(start)

if __name__ == '__main__':
    M = MyList([2,4,7,8,9,2,3,4])
    print(M.list)

在调试模式下,我得到了。

enter image description here

是的。

但是当我在Mylist中重载 str 时(先前的代码相同)

    def __str__(self):
        return "__repr__ method: {0}".format(self.list)

我明白了

enter image description here

如果我在类中将 str 替换为 repr 方法,则没有任何改变。

但是如果我添加 getattr setattr

class MyList:
    def __init__(self, start=[]):
        print('__init__ method')
        self.list = list(start)

    def __repr__(self):
        return "__repr__ method: {0}".format(self.list)

    def __getattr__(self, item):
        print('__getattr__ method')
        return getattr(self.list, item)

    def __setattr__(self, key, value):
        print('__setattr__ method')
        if key == 'boolAttr':
            self.__dict__['boolAttr'] = False
        else:
            self.__dict__[key] = value

if __name__ == '__main__':
    M = MyList([2,4,7,8,9,2,3,4])
    print(M.list)

Python崩溃,我收到循环消息“ __getattr__ method

在此之后,如果我在Mylist中删除 str (或 repr ),则一切正确。

我不明白,此实现中的 str repr 方法有什么问题

0 个答案:

没有答案
相关问题