实现__repr__
为类Foo
与成员变量x
和y
,有没有办法自动填充字符串?例如不工作:所有成员变量的Python __repr__
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(**self.__dict__)
>>> foo = Foo(42, 66)
>>> print(foo)
IndexError: tuple index out of range
而另:
from pprint import pprint
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(pprint(self.__dict__))
>>> foo = Foo(42, 66)
>>> print(foo)
{'x': 42, 'y': 66}
Foo(None)
是的,我可以将方法定义
def __repr__(self):
return "Foo({x={}, y={}})".format(self.x, self.x)
,但是当有许多成员变量这得到乏味。
不错的一个!真正的优雅。 – Ding
非常感谢! – BoltzmannBrain