Can we overload the behavior of a class object

I know that we can overload the behavior of class instances, for example. -

class Sample(object): pass s = Sample() print s <__main__.Sample object at 0x026277D0> print Sample <class '__main__.Sample'> 

We can change the result of print s :

 class Sample(object): def __str__(self): return "Instance of Sample" s = Sample() print s Instance of Sample 

Can I change the result of print Sample ?

+6
source share
1 answer

You can use the metaclass :

 class SampleMeta(type): def __str__(cls): return ' I am a Sample class.' 

Python 3:

 class Sample(metaclass=SampleMeta): pass 

Python 2:

 class Sample(object): __metaclass__ = SampleMeta 

Output:

 I am a Sample class. 

A metaclass is a class of a class. Its relation to a class is similar to the relation to an instance of a class. The same class statement is used. The inherited form of type instead of object makes it a metaclass. By convention, self is replaced with cls .

+6
source

All Articles