Methods for Python classes representation
Asked Answered
C

4

5

I know that methods __repr__ and __str__ exist to give a formal and informal representation of class instances. But does an equivalent exist for class objects too, so that when the class object is printed, a nice representation of it could be shown?

>>> class Foo:
...     def __str__(self):
...         return "instance of class Foo"
...
>>> foo = Foo()
>>> print foo
instance of class Foo
>>> print Foo
__main__.Foo
Catricecatrina answered 23/2, 2011 at 1:34 Comment(0)
S
6

When you call print(foo), foo's __str__ method is called. __str__ is found in the class of foo, which is Foo.

Similarly, when you call print(Foo), Foo's __str__ method is called. __str__ is found in the class of Foo, which is normally type. You can change that using a metaclass:

class FooType(type):
    def __str__(cls):
        return 'Me a Foo'
    def __repr__(cls):
        return '<Foo>'

class Foo(object):
    __metaclass__=FooType
    def __str__(self):
        return "instance of class Foo"

print(Foo)
# Me a Foo

print(repr(Foo))
# <Foo>
Scuffle answered 23/2, 2011 at 4:22 Comment(0)
S
1

You might be able to do this with a metaclass, but AFAIK, there's no general solution for normal classes.

If it's just your own classes, you could adopt a coding standard of including a particular class variable with your metadata, ie:

class Whatever(object):
    classAuthor = "me"
    classCreated = "now"

Or if you're using a python that supports class decorators, you could use a decorator to annotate it for you automatically or enforce that the metadata is there.

But... maybe you just want AClass.__name__ ?

Singley answered 23/2, 2011 at 2:7 Comment(0)
S
0

In my view, it's a good thing that you can't make a custom repr string for classes; the point of a class is to create instances of that class.

Solvolysis answered 23/2, 2011 at 1:38 Comment(2)
In some situations it can be useful imho. For example if you want to print a list of classes and provide for them custom descriptions instead of their full name.Catricecatrina
In that case you should use str instead of repr. It's not necessary but often nice to have the latter be the actual Python source code representation of the value so that eval(repr(x)) == x.Holm
T
0

You cannot use the __repr__ or __str__ on the class type but you can use the docstring to present information about the class

>>> class Foo:
...     """Foo's description"""
...     def __str__(self):
...         return "instance of class Foo"
... 
>>> foo = Foo()
>>> print foo
instance of class Foo
>>> print Foo.__doc__
Foo's description
>>> Foo.__doc__
"Foo's description"
Topliffe answered 23/2, 2011 at 2:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.