【发布时间】:2017-11-19 14:00:20
【问题描述】:
用成员变量x 和y 为类Foo 实现__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)
但是当有很多成员变量时,这会变得乏味。
【问题讨论】:
标签: python string-formatting repr