2017-06-16 43 views
1

实现__repr__为类Foo与成员变量xy,有没有办法自动填充字符串?例如不工作:所有成员变量的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) 

,但是当有许多成员变量这得到乏味。

回答

5

时,我想类似的东西,我用这个作为一个mixin。

+0

不错的一个!真正的优雅。 – Ding

+0

非常感谢! – BoltzmannBrain

0

我想你想是这样的:

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's answer,您可以通过

return "{}({!r})".format(self.__class__.__name__, self.__dict__) 

一个更通用的方法替换上面的行。

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,和所有的属性: