Вопрос

Given this simple class:

class Foo(object):
    def __init__(self,a=None):
        self.a = a
    def __repr__(self):
        return "Foo(a='{self.a}')".format(self=self)

I'm wondering if there is a simple way to get the __repr__ to return different formatting depending on the type of a:

Foo('some_string') # if a is a string
Foo(5)             # if a is the integer 5
Foo(None)          # if a is None

Obviously, for a single attribute I could test and have different output strings but I am thinking that someone must have tackled this before me. Specifically, I have several attributes that can be strings or None and I don't see that writing complicated logic for my __repr__ makes much sense.

Это было полезно?

Решение

Just use the repr() of self.a:

return "Foo(a={self.a!r})".format(self=self)

The !r tells .format() to call repr() on self.a, instead of calling __format__() on the value, see Format String syntax:

>>> '{!r}'.format(0)
'0'
>>> '{!r}'.format('foo')
"'foo'"

Demo:

>>> Foo(0)
Foo(a=0)
>>> Foo('foo')
Foo(a='foo')
>>> Foo(None)
Foo(a=None)

Другие советы

While I accepted Martijn's answer, I wanted to explicitly show the results of his suggestion a little more clearly:

>>> class Foo(object):
...     def __init__(self, a=None, b=None):
...         self.a = a
...         self.b = b
...     def __repr__(self):
...         return 'Foo(a={self.a!r}, b={self.b!r})'.format(self=self)
...      
>>> Foo(a='a')
Foo(a='a', b=None)
>>> Foo(a=5)
Foo(a=5, b=None)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top