作者:ckx1989 | 来源:互联网 | 2023-02-01 08:15
实现__repr__
了一类Foo
有成员变量x
和y
,是有办法来自动填充字符串?不起作用的示例:
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)
但是当有许多成员变量时,这会变得乏味.
1> Ned Batcheld..:
当我想要这样的东西时,我用它作为mixin:
class SimpleRepr(object):
"""A mixin implementing a simple __repr__."""
def __repr__(self):
return "<{klass} @{id:x} {attrs}>".format(
klass=self.__class__.__name__,
id=id(self) & 0xFFFFFF,
attrs=" ".join("{}={!r}".format(k, v) for k, v in self.__dict__.items()),
)
它给出了类名,(缩短的)id和所有属性.