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

Peter Otten __peter__ at web.de
Fri Aug 20 20:40:33 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()
> 
> Regards,
> 
> Neil

Classes are objects. You have to define the __str__() method in the object's
class - for a class that would be the metaclass. Now here:

>>> class FooType(type):
...     def __str__(self):
...             return "custom text for class %s" % self.__name__
...
>>> class Foo:
...     __metaclass__ = FooType
...     def __str__(self):
...             return "custom text for %s instance" %
self.__class__.__name__
...
>>> print Foo()
custom text for Foo instance
>>> print Foo
custom text for class Foo
>>>

Peter




More information about the Python-list mailing list