根据本文和答案,另一种实现方法是通过自定义元类。这将按以下方式工作(在python 2.7中进行了测试):
# define a new Metaclass which overrides the "__call__" function
class NewInitCaller(type):
def __call__(cls, *args, **kwargs):
"""Called when you call MyNewClass() """
obj = type.__call__(cls, *args, **kwargs)
obj.new_init()
return obj
# then create a new class with the __Metaclass__ set as our custom Metaclass
class MyNewClass(object):
__Metaclass__ = NewInitCaller
def __init__(self):
print "Init class"
def new_init(self):
print "New init!!"
# when you create an instance
a = MyNewClass()
>>> Init class
>>> New init!!
基本思想是:
当您调用MyNewClass()
它搜索元类时,会发现您已定义NewInitCaller
此函数MyNewClass
使用创建实例type
,
该实例将自己运行__init__
(打印“ Init类”)。