Python 中的类型对象

问题描述 投票:0回答:1

在 Python 中,我认为对象可用于类型类,对象名称与类名称相同,即类型。 我有一个关于这个的问题......当我们使用类型(类名,基类,att_dict)创建类时,实际上调用了类型中的call()方法。 这最终会产生给定类的对象(例如:

type("some_class", (),{}
)。

在这个语句中,

type("some_class", (),{})
,类型是对象(属于类类型) 在这里,通过使用类型对象调用call()。

我认为 type() 也是一个类方法。所以在这种情况下,理想情况下它也可以被以下调用:

type.__call__("some_class", (),{})

但这是错误的。

TypeError: descriptor '__call__' requires a 'type' object but received a 'str'

同时,以下效果很好。

>>> class sample:
...     @classmethod
...     def __call__(cls,a):
...         return a*a
...
>>> sample.__call__(10)
100

所以我对上面的错误信息感到困惑..比如:我的理解哪里不正确? 有人可以帮帮我吗?

谢谢

python call metaclass
1个回答
0
投票

有几个部分需要我们一一说。

你的困惑来自于这句话:

我认为 type() (或更具体地说是

__call__
)也是一种类方法。

No

__call__
是普通方法(又名实例方法)。这意味着如果您从类本身调用它,则需要传递第一个参数。 (这是 descriptor 对象的行为——方法是描述符)

所以:

type("some_class", (), {})
# or
type.__call__(type, "some_class", (), {})

另一件可能有点晦涩的事情是

type
是它自己的实例。这意味着当您在
type
前面加上括号时,
__call__
类的
type
将被执行。 “像正常方法一样”。

type metaclass   ->   custom class   ->   instance of the custom class


type:
    instance "and" class of itself. class of the custom class
custom class:
    instance of type. class of 'instance of the custom class'
instance of the custom class:
    instance of the custom class.

这最终会产生一个“给定”(?)类的对象

让我们说清楚。这最终会产生一个对象,它本身就是一个类(一种类型),它的名字是

"some_class"
。这是
type
元类的实例。


同时,以下效果很好。

是的,因为你故意让它成为一个类方法。

__call__
元类的
type
不是类方法。

© www.soinside.com 2019 - 2024. All rights reserved.