Special Method and Class

Jack Diederich jack at performancedrivers.com
Thu Apr 8 15:26:24 EDT 2004


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 ?
> > Here a simple example :
> > 
> > >>> class Test(object):
> > ...     def __repr__(cls):
> > ...         return "<special %s>" % cls.__name__
> > ...     __repr__ = classmethod(__repr__)
> > ...
> > >>> print repr(Test)
> > <class '__main__.Test'>
> This is your clue, this didn't print <special Test>
> for the same reason the __iter__ does work below.
> The special __method__'s only work for instances of
> the class and not for the class itself.
> 
> >>> print repr(Test)
> <class '__main__.Test'>
> >>> print repr(Test())
> <special Test>

This deserves a better explanation,
repr(some_instance) will call the __repr__ method of the thing that foo
is an instance of. 

You normally think of objects as instances of a class, but classes are 
also an instances of a type.  Now you're in metaclass territory which 
is overkill for what you want to do.

illustration:

class MetaFoo(type):
  """define our own type"""
  def __repr__(self):
    return 'this is an instance of MetaFoo'

class Foo(object):
  """define a class which is an instance of our own type"""
  __metaclass__ = MetaFoo
  def __repr__(self):
    return 'this is an instance of Foo'

>>> repr(Foo)
'this is an instance of MetaFoo'
>>> repr(Foo())
'this is an instance of Foo'

I can't think of a reason that classmethod() would be useful or legal
when applied to magic methods like __repr__.  Maybe it should throw
an exception instead.  It is possible to do things with a classmethod
__repr__ but it is a very obscure way to get the end effect.

def Foo(object):
  which = 'class'
  def __init__(self):
    self.which = 'instance'
  def __repr__(cls):
    return "Foo with which of " + cls.which
  __repr__ = classmethod(__repr__)

>>>repr(Foo())
'Foo with which of class'


-jackdied




More information about the Python-list mailing list