Defining __repr__(self) to be created dynamically in python
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__
精彩评论