實現__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