36

I know we can overload behavior of instances of a class, e.g. -

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 we change the result of print Sample?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
AlokThakur
  • 3,599
  • 1
  • 19
  • 32

1 Answers1

14

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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161