在Python中动态创建__repr__(self)的定义

3 投票
1 回答
755 浏览
提问于 2025-04-16 20:59

我有一个类

class FooBar(object):
    def __repr__(self):
        pass

我想实现一个叫做 __repr__ 的函数。因为我把 FooBar 当作一个方便的容器,并且我会动态地添加一些属性,所以我想把 __repr__ 也动态生成。(如果这样做不好,请告诉我并给我讲解一下 :-))

我想到了类似这样的做法:

def __repr__(self):
    return '<FooBar({WHAT IS ELEGANT AND GOES HERE?})>'.format(**self.__dict__)

有什么建议吗?谢谢!

1 个回答

1
>>> '<FooBar({!r})>'.format({'a':1, 'b':2})
"<FooBar({'a': 1, 'b': 2})>"
'<FooBar({!r})>'.format(vars(self))

在Python2.6中,你需要使用 {0!r} 这个写法。

我觉得这个写法比直接提到 .__dict__ 要好。

撰写回答