2017-06-16 41 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,和所有的屬性: