Skip to content

Instantly share code, notes, and snippets.

@aGHz
Created October 30, 2012 14:48
Show Gist options
  • Select an option

  • Save aGHz/3980643 to your computer and use it in GitHub Desktop.

Select an option

Save aGHz/3980643 to your computer and use it in GitHub Desktop.
Strange behaviour with repr() and __repr__ in Python

The Python builtin repr() doesn't seem to take into account the object's __repr__

class Foo(object):
    __repr__ = lambda self: "class"

    def __init__(self, a):
        self.__repr__ = lambda: "object"

foo = Foo('object')
print foo                 # "class"
print repr(foo)           # "class"
print foo.__repr__()      # "object"

Also there's something strange with overriding __repr__ in __init__, I can't give it a self parameter:

class Foo(object):
    def __init__(self, a):
        self.__repr__ = lambda self: "object"

foo = Foo('object')
print foo.__repr__()

Traceback (most recent call last):
  File "repr.py", line 6, in <module>
    print foo.__repr__()
TypeError: <lambda>() takes exactly 1 argument (0 given)

Shouldn't Python just pass in foo as self?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment