Python __repr__ for all member variables

徘徊边缘 提交于 2020-02-27 02:25:10

问题


Implementing __repr__ for a class Foo with member variables x and y, is there a way to automatically populate the string? Example that does not work:

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

And another:

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)

Yes I could define the method as

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

but this gets tedious when there are many member variables.


回答1:


I use this as a mixin when I want something like that:

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

It gives the class name, the (shortened) id, and all of the attributes.




回答2:


I think you want something like this:

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

This will add repr(self.__dict__) in the string, using !r in a format specifier tells format() to call the item's __repr__().

See the "Conversion field" here: https://docs.python.org/3/library/string.html#format-string-syntax


Based on Ned Batchelder's answer, you can replace the line above by

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

for a more generic approach.




回答3:


Nice example!

for pretty output better to place simple return "\n{!r}".format(self.__dict__) and in root full print return "Class name: '{}' \n{!r}".format(self.__class__.__name__, self.__dict__)



来源:https://stackoverflow.com/questions/44595218/python-repr-for-all-member-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!