我真的不明白基础元类是如何工作的(又名type).有没有人知道它的功能的纯python模拟?
python文档经常为C级代码执行此操作,这些代码很难用英语完全描述(例如,请参阅解释__getattribute__),但不适用于type.
我知道怎么开始.由于定义type使用类型的子类的行为有点像说"类型工作方式类型工作",我定义了一个鸭类型元类.它有些功能,但还不够.
class MetaClassDuck(object):
@classmethod
def __new__(self, mcs, name, bases, attrs):
"""Create a new class object."""
newcls = super(MetaClassDuck, self).__new__(mcs)
newcls.__dict__.update(attrs)
newcls.__name__ = name
newcls.__bases__ = bases
return newcls
def __call__(cls, *args, **kwargs):
"""Calling a class results in an object instance."""
###########################################################
# Fill in the blank:
# I don't see a way to implement this without type.__new__
###########################################################
return newobj
class MyClass(object):
__metaclass__ = MetaClassDuck
one = 1
_two = 2
@property
def two(self):
return self._two
# This bit works fine.
assert type(MyClass) is MetaClassDuck
assert MyClass.one == 1
assert isinstance(MyClass.two, property)
myobj = MyClass()
# I crash here:
assert myobj.one == 1
assert myobj.two == 2
class MyClass2(MyClass):
three = 3
assert type(MyClass2) is MetaClassDuck
assert MyClass2.one == 1
assert isinstance(MyClass2.two, property)
assert MyClass2.three == 3
myobj2 = MyClass2()
assert myobj2.one == 1
assert myobj2.two == 2
assert myobj2.three == 3
Run Code Online (Sandbox Code Playgroud)
__new__负责创建新实例,而不是__call__. __call__只是将实例创建工作传递给__new__,并返回__new__返回的内容,__init__如果需要则调用。
回答这个type问题(双关语)的最好方法是深入研究 C 代码。只需下载源代码,解压它或vim Objects/typeobject.c任何您用来阅读和摆弄代码的东西。
如果您查看它,您会发现type元类的所有组件的 C 实现。__new__太大了,FIY。
def __call__(cls, *args, *kwds):看起来像:
static PyObject *
type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *obj;
if (type->tp_new == NULL) {
PyErr_Format(PyExc_TypeError,
"cannot create '%.100s' instances",
type->tp_name);
return NULL;
}
obj = type->tp_new(type, args, kwds);
if (obj != NULL) {
# /* Ugly exception: when the call was type(something),
# don`t call tp_init on the result. */
if (type == &PyType_Type &&
PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
(kwds == NULL ||
(PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
return obj;
# /* If the returned object is not an instance of type,
# it won`t be initialized. */
if (!PyType_IsSubtype(obj->ob_type, type))
return obj;
type = obj->ob_type;
if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
type->tp_init != NULL &&
type->tp_init(obj, args, kwds) < 0) {
Py_DECREF(obj);
obj = NULL;
}
}
return obj;
}
Run Code Online (Sandbox Code Playgroud)
#由我添加,以帮助 Stackoverflow 的语法荧光笔正确呈现注释
这只是我理解的Python式解释type.__call__。这不是它的重新实现!
我可能忽略了一些方面,因为我对 PyC API 相当陌生,所以请随时纠正我。但我会按如下方式实现它:
def __call__(cls, *args, **kwds):
#We`ll be naming the class reference cls here, in the C code it's called type.
try:
obj = cls.__new__(cls, args, kwds)
except AttributeError:
#The code first checks whether there is a __new__ method, we just catch the AttributeError
#exception.
raise TypeError('cannot create {} instances', cls.__name__)
else:
#The last if block checks that no errors occurred *inside* cls.__new__
#(in the C code: type->tp_new)
cls.__init__(obj, args, kwds)
#The last if block checks whether any exception occurred while calling __init__
#(return NULL or return -1 tells the calling function that an error/exception occurred,
#IDK the difference between the two.)
return obj
Run Code Online (Sandbox Code Playgroud)
__new__实现(称为 type_new)| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |