【问题标题】:Python __repr__ for all member variablesPython __repr__ 用于所有成员变量
【发布时间】:2017-11-19 14:00:20
【问题描述】:

用成员变量xy 为类Foo 实现__repr__,有没有办法自动填充字符串?不起作用的示例:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Foo({})".format(**self.__dict__)

>>> foo = Foo(42, 66)
>>> print(foo)
IndexError: tuple index out of range

还有一个:

from pprint import pprint
class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Foo({})".format(pprint(self.__dict__))

>>> foo = Foo(42, 66)
>>> print(foo)
{'x': 42, 'y': 66}
Foo(None)

是的,我可以将方法定义为

    def __repr__(self):
        return "Foo({x={}, y={}})".format(self.x, self.x)

但是当有很多成员变量时,这会变得乏味。

【问题讨论】:

    标签: python string-formatting repr


    【解决方案1】:

    当我想要这样的东西时,我将它用作混合:

    class SimpleRepr(object):
        """A mixin implementing a simple __repr__."""
        def __repr__(self):
            return "<{klass} @{id:x} {attrs}>".format(
                klass=self.__class__.__name__,
                id=id(self) & 0xFFFFFF,
                attrs=" ".join("{}={!r}".format(k, v) for k, v in self.__dict__.items()),
                )
    

    它给出了类名、(缩短的)id 和所有属性。

    【讨论】:

    • 不错的一个!真正的优雅。
    【解决方案2】:

    我想你想要这样的东西:

        def __repr__(self):
            return "Foo({!r})".format(self.__dict__)
    

    这将在字符串中添加repr(self.__dict__),在格式说明符中使用!r 告诉format() 调用项目的__repr__()

    在此处查看“转化字段”:https://docs.python.org/3/library/string.html#format-string-syntax


    基于Ned Batchelder's answer,您可以将上面的行替换为

    return "{}({!r})".format(self.__class__.__name__, self.__dict__)
    

    为了更通用的方法。

    【讨论】:

    • 如果self 引用自己,这样的实现将导致无限循环,因此您必须先过滤self.__dict__
    【解决方案3】:

    很好的例子!

    为了漂亮的输出更好 放置简单return "\n{!r}".format(self.__dict__) 并在根目录下完整打印return "Class name: '{}' \n{!r}".format(self.__class__.__name__, self.__dict__)

    【讨论】:

      猜你喜欢
      • 2010-11-26
      • 1970-01-01
      • 2023-03-09
      • 2014-07-29
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2011-02-05
      相关资源
      最近更新 更多