Python: changing class print

Is it possible in python to change what is printed for classes. I know that if we provide the __str__ __unicode__ __str__ , we can change the way the class instances are output. But I want to do it for the class.

For example:

 class A(object): def __str__(self): return 'hello' a = A() print a 

will print hello . Is it possible to change the print A behavior, which by default prints something like <class '__main__.A'>

Refresh . I think I could also explain the context. I am trying to create MySQL queries, and I have classes representing tables. Each of these table classes has a class variable containing the name of the table. So what I want to do is to pass the Class as parameter to cursor.execute and replace the tablenames tags in the query.

+7
source share
2 answers

Yes by providing a metaclass . This is a bad idea because metaclasses do not compose very well, and it is magical and confusing.

 >>> class A(type): ... def __repr__(self): ... return '<this is not a class!>' ... >>> class B(object): ... __metaclass__ = A ... >>> print B <this is not a class!> 

(you can also change __str__ , it depends on the semantics of what it is)


You updated the message to talk about generating SQL queries from the class. Instead of changing str(Class) , why not use Class.__name__ (i.e. the Name that you defined) instead, or perhaps Class.table_name (i.e. Any attribute of the class that you define for each class)? The ability to go through classes and automate their work, since the names of tables that do not belong to the <class 'foo.x'> form are potentially very confusing for future readers of your code, because it is not clear that this should work out of context. The reader must remember that metaclassical hacks were involved (a relatively rare thing, although not in ORM!) And what the metaclass did. On the contrary, just passing Class.table_name instead of Class makes it very obvious what is happening.

+5
source

Simple with metaclass. Metaclass refers to a class, that class refers to an instance

 class A_meta(type): def __str__(cls): return 'foobar' class A(object): __metaclass__ = A_meta def __str__(self): return 'hello' a = A() print a print A 
+4
source

All Articles