python 2.2 question...

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Sep 25 09:22:08 EDT 2001


"Paolo Invernizzi" <paoloinvernizzi at dmsware.com> writes:

> I've wondering if there is a solution in 2.2 for this question... (or in 2.1
> ;)
> 
> I want a custom str rapresentation for a class object... 

Perhaps you could elaborate why you want this? Would it be sufficient
if the object isn't a class object at all, but merely callable? Then,
in 2.1, you can do

class Meta:
  def __init__(self,klass):
    self.klass=klass
  def __repr__(self):
    return "special"
  def __call__(self,*args):
    return self.klass(*args)

class _Klasse:
  pass

Klasse = Meta(_Klasse)

If you absolutely want to do this with 'true' meta classes, this is
the 2.2 way of writing it:

>>> class t(type):
...   def __repr__(self):return 'special'
... 
>>> class c(object):
...   __metaclass__=t
... 
>>> c
special
>>> o=c()
>>> o
<__main__.c object at 0x18da10>

So a metaclass ought to be similar to the type type (which is bound to
the type builtin); thus t inherits from type. Furthermore, the proper
class c has object as a base class, but t as the metaclass.

Regards,
Martin



More information about the Python-list mailing list