Methods for Python classes representation

女生的网名这么多〃 提交于 2019-12-04 07:20:19
unutbu

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>

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__ ?

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.

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!