所有成员变量的Python __repr__

Bol*_*ain 4 python repr string-formatting

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

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
Run Code Online (Sandbox Code Playgroud)

而另一个:

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)
Run Code Online (Sandbox Code Playgroud)

是的我可以将方法定义为

    def __repr__(self):
        return "Foo({x={}, y={}})".format(self.x, self.x)
Run Code Online (Sandbox Code Playgroud)

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

Ned*_*der 12

当我想要这样的东西时,我用它作为mixin:

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()),
            )
Run Code Online (Sandbox Code Playgroud)

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


Nat*_*ini 6

我想你想要这样的东西:

    def __repr__(self):
        return "Foo({!r})".format(self.__dict__)
Run Code Online (Sandbox Code Playgroud)

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

请参阅此处的“转换字段”:https : //docs.python.org/3/library/string.html#format-string-syntax


根据Ned Batchelder 的回答,您可以将上面的行替换为

return "{}({!r})".format(self.__class__.__name__, self.__dict__)
Run Code Online (Sandbox Code Playgroud)

对于更通用的方法。