Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why does a dynamically added __repr__ method not override the default [duplicate]

Tags:

python

Where is python getting the repr which is still yielding 'foo' even after the original repr method has been overwritten?

class Test(object):
    def __init__(self, name, number_array): 
        self.name = name
        self.number_array = number_array
    def __repr__(self):
        return str(self.name) 

def custom_repr(self): 
    return str(self.name*4)

>>> A = Test('foo', [1,2])
>>> A
foo
>>> A.__repr__ = custom_repr.__get__(A, A.__class__)
>>>A.__repr__()
foofoofoofoo
>>>A
foo
like image 416
user3467349 Avatar asked Sep 26 '14 01:09

user3467349


People also ask

What is the purpose of the __ repr __ method?

According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.

What is __ repr in Python?

Python repr() Function returns a printable representation of an object in Python.

Is repr () a python built in function?

Definition. The Python repr() built-in function returns the printable representation of the specified object as a string.


2 Answers

As explained in Special Method Lookup:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary … In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass

(The part I've snipped out explains the rationale behind this, if you're interested in that.)

Python doesn't document exactly when an implementation should or shouldn't look up the method on the type; all it documents is, in effect, that implementations may or may not look at the instance for special method lookups, so you shouldn't count on either.

But, as you can guess from your test results, in the CPython implementation, __repr__ is one of the functions looked up on the type.

like image 61
abarnert Avatar answered Nov 02 '22 05:11

abarnert


__repr__ is looked up directly on the class, not on the instance, when it's looked up by repr or similar (such as when it's called by the interactive interpreter). If you must monkey-patch a repr, do it on the class (but please don't).

This same basic rule applies to most dunder methods.

like image 32
Mike Graham Avatar answered Nov 02 '22 04:11

Mike Graham