classes are objects... so how can we custom print them: we need a classmethod syntax

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Fri Aug 20 20:30:22 CEST 2004


Neil Zanella wrote:
> Hello,
> 
> In Python, classes are objects. But there is no way to custom print a class
> object. This would require some syntax such as the one commented out below:
> With the current "foo = classmethod(foo)" mechanism custom printing for
> class objects is not possible.
> 
> #!/usr/bin/python
> 
> class Foo:
>   def __str__(self):
>     return "foo"
>   #def classmethod __str__(cls):
>   #  return "pythons bite"
> 
> foo = Foo()
> s = "hello %s!" % foo # custom text here
> print s
> 
> print Foo # no custom text here possible it seems, unless we call
>           # a staticmethod such as Foo.printMe()

You need Metaclasses for that. Consider:

>>> class PrintTest(object):
...     class __metaclass__(type):
...         def __str__(self):
...             return "I'm a PrintTest"
...
>>> print PrintTest
I'm a PrintTest
>>>

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list