Can we overload behavior of class object
This question already has an answer here:
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 .
上一篇: 使用isinstance()可以覆盖类型
下一篇: 我们可以重载类对象的行为吗?
