Can we overload behavior of class object

This question already has an answer here:

  • What are metaclasses in Python? 14 answers

  • 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 class statement is used. Inheriting form type instead from object makes it a metaclass. By convention self is replaced by cls .

    链接地址: http://www.djcxy.com/p/6988.html

    上一篇: 使用isinstance()可以覆盖类型

    下一篇: 我们可以重载类对象的行为吗?