自动 __repr__ 方法

31

我希望能够对任何类进行简单的表示,例如 { property = value },是否有自动的 __repr__ 方法?

7个回答

39

最简单的方法:

def __repr__(self):
    return str(self.__dict__)

15

是的,你可以创建一个名为 "AutoRepr" 的类,并让所有其他类都继承它:

>>> class AutoRepr(object):
...     def __repr__(self):
...         items = ("%s = %r" % (k, v) for k, v in self.__dict__.items())
...         return "<%s: {%s}>" % (self.__class__.__name__, ', '.join(items))
... 
>>> class AnyOtherClass(AutoRepr):
...     def __init__(self):
...         self.foo = 'foo'
...         self.bar = 'bar'
...
>>> repr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"

请注意,上面的代码将无法很好地处理直接或间接引用自身的数据结构。作为替代,您可以定义一个适用于任何类型的函数:

>>> def autoRepr(obj):
...     try:
...         items = ("%s = %r" % (k, v) for k, v in obj.__dict__.items())
...         return "<%s: {%s}." % (obj.__class__.__name__, ', '.join(items))
...     except AttributeError:
...         return repr(obj)
... 
>>> class AnyOtherClass(object):
...     def __init__(self):
...         self.foo = 'foo'
...         self.bar = 'bar'
...
>>> autoRepr(AnyOtherClass())
"<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
>>> autoRepr(7)
'7'
>>> autoRepr(None)
'None'
请注意,上述函数故意没有定义为递归的形式,这是出于前面提到的原因。

__dict__不显示class AnyOtherClass(object):foo = 'hello'。 - Igor Golodnitsky

7

好的,我尝试了其他答案并得到了一个非常漂亮的解决方案:

class data:
    @staticmethod
    def repr(obj):
        items = []
        for prop, value in obj.__dict__.items():
            try:
                item = "%s = %r" % (prop, value)
                assert len(item) < 20
            except:
                item = "%s: <%s>" % (prop, value.__class__.__name__)
            items.append(item)

        return "%s(%s)" % (obj.__class__.__name__, ', '.join(items))

    def __init__(self, cls):
        cls.__repr__ = data.repr
        self.cls = cls

    def __call__(self, *args, **kwargs):
        return self.cls(*args, **kwargs)

您可以将其用作装饰器:
@data
class PythonBean:
    def __init__(self):
        self.int = 1
        self.list = [5, 6, 7]
        self.str = "hello"
        self.obj = SomeOtherClass()

并且可以轻松获得一个智能的__repr__

PythonBean(int = 1, obj: <SomeOtherClass>, list = [5, 6, 7], str = 'hello')

任何递归类都可以使用此方法,包括树形结构。如果您尝试在类中放置自引用 self.ref = self,该函数将会尝试(成功地)处理大约一秒钟。
当然,始终要注意您的老板 - 我的老板可能不喜欢这样的语法糖))

不支持继承。 - David Davó

5
你是指
__dict__

?


3
class MyClass:
    def __init__(self, foo: str, bar: int):
        self.foo = foo
        self.bar = bar
        self._baz: bool = True

    def __repr__(self):
        f"{self.__class__.__name__}({', '.join([f'{k}={v!r}' for k, v in self.__dict__.items() if not k.startswith('_')])})"

mc = MyClass('a', 99)

print(mc)
# MyClass(foo='a', bar=99)
# ^^^ Note that _baz=True was hidden here

1
我使用这个辅助函数来为我的类生成repr。它很容易在unittest函数中运行,例如:
def test_makeRepr(self):
    makeRepr(Foo, Foo(), "anOptional space delimitedString ToProvideCustom Fields")

这应该会在控制台输出多个潜在的repr,然后你可以将其复制/粘贴到你的类中。
def makeRepr(classObj, instance = None, customFields = None):
    """Code writing helper function that will generate a __repr__ function that can be copy/pasted into a class definition.

    Args:
        classObj (class):
        instance (class):
        customFields (string):

    Returns:
        None:

    Always call the __repr__ function afterwards to ensure expected output.
    ie. print(foo)

    def __repr__(self):
        msg = "<Foo(var1 = {}, var2 = {})>"
        attributes = [self.var1, self.var2]
        return msg.format(*attributes)
    """ 
    if isinstance(instance, classObj):
        className = instance.__class__.__name__
    else:
        className=classObj.__name__

    print('Generating a __repr__ function for: ', className,"\n")
    print("\tClass Type: "+classObj.__name__, "has the following fields:")
    print("\t"+" ".join(classObj.__dict__.keys()),"\n")
    if instance:
        print("\tInstance of: "+instance.__class__.__name__, "has the following fields:")
        print("\t"+" ".join(instance.__dict__.keys()),"\n")
    else:
        print('\tInstance of: Instance not provided.\n')

    if customFields:
        print("\t"+"These fields were provided to makeRepr:")
        print("\t"+customFields,"\n")
    else:
        print("\t"+"These fields were provided to makeRepr: None\n")
    print("Edit the list of fields, and rerun makeRepr with the new list if necessary.\n\n")

    print("repr with class type:\n")
    classResult = buildRepr( classObj.__name__, " ".join(classObj.__dict__.keys()))
    print(classResult,"\n\n")

    if isinstance(instance, classObj):
        instanceResult = buildRepr( instance.__class__.__name__, " ".join(instance.__dict__.keys()))
    else:
        instanceResult = "\t-----Instance not provided."
    print("repr with instance of class:\n")
    print(instanceResult,"\n\n") 

    if customFields:
        customResult = buildRepr( classObj.__name__, customFields)
    else:
        customResult = '\t-----Custom fields not provided'
    print("repr with custom fields and class name:\n")
    print(customResult,"\n\n")    

    print('Current __repr__')
    print("Class Object: ",classObj)
    if instance:
        print("Instance: ",instance.__repr__())
    else:
        print("Instance: ", "None")


def buildRepr(typeName,fields):
    funcDefLine = "def __repr__(self):"
    msgLineBase  = '    msg = "<{typename}({attribute})>"'
    attributeListLineBase = '    attributes = [{attributeList}]'
    returnLine = '    return msg.format(*attributes)'
    x = ['self.' + x for x in fields.split()]
    xResult = ", ".join(x)
    y = [x + ' = {}' for x in fields.split()]
    yResult = ', '.join(y)
    msgLine = msgLineBase.format(typename = typeName, attribute = yResult)
    attributeListLine = attributeListLineBase.format(attributeList = xResult) 
    result = "{declaration}\n{message}\n{attributes}\n{returnLine}".format(declaration = funcDefLine,
                                                                       message = msgLine,
                                                                       attributes = attributeListLine,
                                                                       returnLine =returnLine )
    return result

0
为了让 @uzi 的回答更清晰,我加入了更多的示例代码。这对于快速编写简单脚本非常有用:
class MyClass:
    def __repr__(self):
        return "MyClass:" + str(self.__dict__)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接