Can we overload behavior of class object [duplicate] Can we overload behavior of class object [duplicate] python-3.x python-3.x

Can we overload behavior of class object [duplicate]


You can use a 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 the class of class. Its relationship to a class is analogous to that of a class to an instance. The same classstatement is used. Inheriting form type instead from object makes it a metaclass. By convention self is replaced by cls.