用成员变量
__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)
但是当有很多成员变量时这会变得乏味。
当我想要类似的东西时,我用它作为混合:
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 和所有属性。
我想你想要这样的东西:
def __repr__(self):
return "Foo({!r})".format(self.__dict__)
这将在字符串中添加
repr(self.__dict__)
,在格式说明符中使用 !r
告诉 format()
调用项目的 __repr__()
。
请参阅此处的“转换字段”:https://docs.python.org/3/library/string.html#format-string-syntax
根据 Ned Batchelder 的回答,您可以将上面的行替换为
return "{}({!r})".format(self.__class__.__name__, self.__dict__)
更通用的方法。
很好的例子!
为了获得漂亮的输出,最好 地方简单
return "\n{!r}".format(self.__dict__)
并以完整字体打印 return "Class name: '{}' \n{!r}".format(self.__class__.__name__, self.__dict__)
通常,
__repr__
意味着您可以复制粘贴结果,并且可以轻松地再次使用它来创建新对象。因此,下面的内容可能看起来有点老套,但可以完成工作。另外,请注意我们需要如何以不同于数字类型的方式对待字符串类型参数。
class Foo:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
repr_str = f"{self.__class__.__name__}"
repr_str += '('
for key, val in self.__dict__.items():
val = f"'{val}'" if isinstance(val, str) else val
repr_str += f"{key}={val}, "
return repr_str.strip(", ") + ')'
>>> foo = Foo(42, 66)
>>> print(foo)
Foo(x=42, y=66)
>>> foo2 = Foo("abc", "xyz")
>>> print(foo2)
Foo(x='abc', y='xyz')