2017-06-16 6 views
1

メンバー変数xyを持つクラスFoo__repr__を実装すると、自動的に文字列を設定する方法はありますか?動作しない例:すべてのメンバー変数のための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

私はミックスインとしてこれを使用します。

+0

いいね!本当の高級。 – Ding

+0

素晴らしい感謝! – BoltzmannBrain

0

:これは、書式指定子で!rを使用して、文字列でrepr(self.__dict__)を追加します

def __repr__(self): 
     return "Foo({!r})".format(self.__dict__) 

は、アイテムの__repr__()を呼び出すためにformat()に指示します。

は、ここで "変換フィールド" を参照してください:Ned Batchelder's answerに基づいてhttps://docs.python.org/3/library/string.html#format-string-syntax


を、あなたは、より一般的なアプローチのために

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、および属性のすべてを与える:私はそのような何かをしたいとき

関連する問題