在Python 3.1中,我在builtins模块中有一个新的内置函数:
__build_class__(...)
__build_class__(func, name, *bases, metaclass=None, **kwds) -> class
Internal helper function used by the class statement.
Run Code Online (Sandbox Code Playgroud)
这个功能有什么作用?如果它是内部的,为什么必须在内置?这个type(name, bases, dict)功能有什么区别?
我正在编写一个元类,我想在 __new__ 和 __init__ 之间调用一个额外的方法。
如果我在 __new__ 之前或 __init__ 之后调用该方法,我可以编写例如
class Meta(type):
def __call__(cls):
ret = type.__call__()
ret.extraMethod()
Run Code Online (Sandbox Code Playgroud)
我的诱惑是写
class Meta(type):
def __call__(cls):
ret = cls.__new__(cls)
ret.extraMethod()
ret.__init__()
return ret
Run Code Online (Sandbox Code Playgroud)
并自己重现 type.__call__ 的功能。但恐怕我省略了 type.__call__ 的一些微妙之处,这将导致在实现我的元类时出现意外行为。
我不能从 __init__ 或 __new__ 调用 extraMethod 因为我希望我的元类的用户能够像在普通 Python 类中一样覆盖 __init__ 和 __new__,但仍然在 extraMethod 中执行重要的设置代码。
谢谢!