Python __repr__用于所有成员变量 [英] Python __repr__ for all member variables
本文介绍了Python __repr__用于所有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为具有成员变量x
和y
的类Foo
实现__repr__
,是否有一种自动填充字符串的方法?无效的示例:
Implementing __repr__
for a class Foo
with member variables x
and y
, is there a way to automatically populate the string? Example that does not work:
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)
是的,我可以将方法定义为
Yes I could define the method as
def __repr__(self):
return "Foo({x={}, y={}})".format(self.x, self.x)
但是当成员变量很多时,这变得很乏味.
but this gets tedious when there are many member variables.
推荐答案
当我想要这样的东西时,我将其用作混合:
I use this as a mixin when I want something like that:
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和所有属性.
It gives the class name, the (shortened) id, and all of the attributes.
这篇关于Python __repr__用于所有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文