Python Class Representation Methods

I know that there are __repr__ and __str__ to give formal and informal representations of class instances. But there is an equivalent for class objects, so when a class object is printed, can its good presentation be shown?

 >>> class Foo: ... def __str__(self): ... return "instance of class Foo" ... >>> foo = Foo() >>> print foo instance of class Foo >>> print Foo __main__.Foo 
+4
source share
4 answers

When you call print(foo) , the foo __str__ method is called. __str__ is in the class foo , which is equal to foo .

Similarly, when you call print(foo) , the foo __str__ method is called. __str__ is in the class foo , which is usually type . You can change this with the 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> 
+5
source

You may be able to do this with a metaclass, but AFAIK is not a general solution for regular classes.

If these are just your own classes, you can adopt a coding standard that includes a specific class variable with your metadata, that is:

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

Or, if you use python that supports class decoders, you can use a decorator to automatically annotate it for you or to ensure that metadata is there.

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

+1
source

In my opinion, it’s good that you cannot create a custom repr string for classes; the point of a class is to instantiate this class.

0
source

You cannot use __repr__ or __str__ for a class type, but you can use docstring to represent class information

 >>> class Foo: ... """Foo description""" ... def __str__(self): ... return "instance of class Foo" ... >>> foo = Foo() >>> print foo instance of class Foo >>> print Foo.__doc__ Foo description >>> Foo.__doc__ "Foo description" 
0
source

Source: https://habr.com/ru/post/1340901/


All Articles