Auto __repr__ method

前端 未结 6 867
囚心锁ツ
囚心锁ツ 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:59

    Well, I played a little bit with other answers and got a very pretty solution:

    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)
    

    You use it as a decorator:

    @data
    class PythonBean:
        def __init__(self):
            self.int = 1
            self.list = [5, 6, 7]
            self.str = "hello"
            self.obj = SomeOtherClass()
    

    and get a smart __repr__ out of the box:

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

    This works with any recursive classes, including tree structures. If you try to put a self-reference in the class self.ref = self, the function will try (successfully) to work it out for about a second.

    Of course, always mind your boss - mine would not like such a syntax sugar ))

提交回复
热议问题