python';s基本元类:纯python模拟?

python';s基本元类:纯python模拟?,python,metaclass,Python,Metaclass,我真的不明白基本元类是如何工作的(akatype)。有人知道纯python的功能类似物吗 python文档通常针对难以用英语完整描述的C级代码(例如,请参阅)执行此操作,但对于type 我知道如何开始。因为使用类型的子类定义type的行为有点像说“type的工作方式与type的工作方式相同”,所以我定义了一个duck类型的元类。它有些效果,但还不够 class MetaClassDuck(object): @classmethod def __new__(self, mcs, n

我真的不明白基本元类是如何工作的(aka
type
)。有人知道纯python的功能类似物吗

python文档通常针对难以用英语完整描述的C级代码(例如,请参阅)执行此操作,但对于
type

我知道如何开始。因为使用类型的子类定义
type
的行为有点像说“type的工作方式与type的工作方式相同”,所以我定义了一个duck类型的元类。它有些效果,但还不够

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

\uuuuu new\uuuuu
负责创建新实例,而不是
\uuuuu call\uuuuu
<代码>\uuuuuuuuuuuuuuuuuu只需将实例创建工作传递给
\uuuuuuuuuuuuuuuuu
,并返回
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu新的返回内容,如果需要,调用

回答这个
类型的
(双关语)问题的最好方法是挖掘C代码。只需下载源代码,将其解压并
vim Objects/typeobject.c
或任何您用来阅读和处理代码的东西

如果您查看它,您将发现
类型
元类的所有组件的C实现<代码>\uuuu新的\uuuu
大得离奇,菲伊

def\uu调用(cls,*args,*kwds):
看起来像:

实际C代码 最后说明
  • 我会检查
    \uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
  • 如果您想了解Python如何在内部工作,请尝试学习C API,然后阅读C源代码
  • 我对PythonC源代码非常陌生,所以我可能忽略了一些东西。请纠正我任何人都知道
我不知道任何Python类似物;但是,如果您想知道具体是什么类型,您需要深入了解
c
源代码

通常,它做任何元类都做的事情:根据各种规范对结果类进行调整

例如:

--> huh = type('my_type', (), {'some_var':7})
--> huh
<class '__main__.my_type'>
--> h = huh()
--> huh.some_var
7
-->huh=type('my_type',(),{'some_var':7})
-->嗯
-->h=huh()
-->嗯,是什么
7.
这里,
type
正在创建一个名为
my\u type
的新类和一个名为
some\u var
的类属性,初始值为
7


如果您想在stdlib中看到一个有用的、虽然有些复杂的元类示例,请查看3.4中的新示例。

您到底想要什么?如果您想了解
类型
的实际功能,最好的方法可能是阅读。如果您想在Python中实现自己的对象系统,尽可能少地使用内置功能,那么如果您对元类、特殊方法查找、描述符等有足够的了解,这是可以实现的,但它不会像真正的类那样与内置系统互操作。如果您想使某些东西与内置API完全兼容,例如
type(thing)
…我不太确定我是否理解您的问题。你想知道吗?你将不得不大量使用
type.\uuuuu new\uuuu
这样的东西,这样做没有什么意义。我试图通过在python中重新实现
type
来澄清它的操作,如上所述。我不知道怎么说得更清楚=/@Two Bitalchest:你是想看看这个
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
--> huh = type('my_type', (), {'some_var':7})
--> huh
<class '__main__.my_type'>
--> h = huh()
--> huh.some_var
7