Auto __repr__ method

前端 未结 6 868
囚心锁ツ
囚心锁ツ 2020-12-30 00:30

I want to have simple representation of any class, like { property = value }, is there auto __repr__?

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 00:58

    Yes, you can make a class "AutoRepr" and let all other classes extend it:

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

    Note that the above code will not act nicely on data structures that (either directly or indirectly) reference themselves. As an alternative, you can define a function that works on any type:

    >>> 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())
    ""
    >>> autoRepr(7)
    '7'
    >>> autoRepr(None)
    'None'
    

    Note that the above function is not defined recursively, on purpose, for the reason mentioned earlier.

提交回复
热议问题