Special Method and Class

Shalabh Chaturvedi shalabh at cafepy.com
Fri Apr 9 20:18:42 EDT 2004


Yermat wrote:

> Jack Diederich wrote:
>> On Thu, Apr 08, 2004 at 02:47:49PM -0400, Jack Diederich wrote:
>> 
>>>On Thu, Apr 08, 2004 at 08:07:01PM +0200, Yermat wrote:
>>>
>>>>Hi all,
>>>>
>>>>Why does special methods not work on class ? Or how to make them work ?

<example snipped>

<useful response snipped>

> I thought that those special method were bounded methods but they are
> not...
> 
>  >>> class toto(object):
> ...     def __init__(self, name):
> ...             self.name = name
> ...     def __repr__(self):
> ...             return "toto('%s')" % self.name
> ...
>  >>>
>  >>> t = toto('titi')
>  >>> repr(t)
> "toto('titi')"
>  >>> t.__repr__
> <function anotherRepr at 0x402dc454>
>  >>> t.__init__
> <bound method toto.__init__ of toto('titi')>

Are you sure you haven't left anything out (like a t.__repr__ = anotherRepr
line somewhere ;) ? On my machine I get:

>>> class C(object):
...     def __repr__(self):
...             return 'C inst'
... 
>>> c = C()
>>> c.__repr__
<bound method C.__repr__ of C inst>
>>>

Yup it's a bound method for sure.

> That also mean that I can't change the __repr__ for only one instance :
>  >>> def anotherRepr(self):
> ...     return "anotherRepr('%s')" % self.name
> ...
>  >>>
>  >>> t.__repr__ = anotherRepr
>  >>>
>  >>> repr(t)
> "toto('titi')"
> 
> 
> Is it really consistent ?
> Should'nt it be also bounded methods even for clas instead of using
> MetaClass ?

Actually this has less to do with bound methods and more to do with how
repr() works. Simple formula for new-style objects:

repr(x) calls x.__class__.__repr__(x)

so repr(C) will call C.__class__.__repr__(C) which is really
type.__repr__(C). 

Also, repr(c) will call c.__class__.__repr__(c), which is really
C.__repr__(c).

If both repr(C) and repr(c) called C.__repr__(), *that* would be
inconsistent (how would one implement C.__repr__()? for the instance or the
class?). A simple solution to be able to override special methods on
instances might be to do (not tested):

class C(object):
    def __repr__(self):
        instrepr = getattr(self, '_instrepr', None)
        if instrepr:
            return instrepr(self)
        else:
            return "default repr"

and then define a function (like anotherRepr above) and assign it to
c._instrepr.

> Yermat

HTH,
Shalabh





More information about the Python-list mailing list