开发者

Defining __repr__(self) to be created dynamically in python

开发者 https://www.devze.com 2023-03-18 02:01 出处:网络
I have a class class FooBar(object): def __repr__(self): pass and I want to implement the __repr__ function. Since I am using FooBar as sort of a handy container and I add some attributes dynamical

I have a class

class FooBar(object):
    def __repr__(self):
        pass

and I want to implement the __repr__ function. Since I am using FooBar as sort of a handy container and I add some attributes dynamically I thought of generating __repr__ dynamically开发者_如何学编程, too. (If this is bad praxis, please explain and enlighten me :-))

I thought of something like:

def __repr__(self):
    return '<FooBar({WHAT IS ELEGANT AND GOES HERE?})>'.format(**self.__dict__)

Any suggestions? Thanks!


>>> '<FooBar({!r})>'.format({'a':1, 'b':2})
"<FooBar({'a': 1, 'b': 2})>"

on Python2.6 you'd have to use {0!r}

I think

'<FooBar({!r})>'.format(vars(self))

is nicer than referring to .__dict__

0

精彩评论

暂无评论...
验证码 换一张
取 消