python中的对象继承

python中的对象继承,python,class,inheritance,metaclass,Python,Class,Inheritance,Metaclass,今天早上我想出了一个奇怪的主意。我们知道,在python中,所有对象都是对象,包括类和函数 别问我为什么要这么做。这是一个关于python的实验。我知道它是从实例继承的 让我们试试: kk=dict() print dir(dict) print dir(kk) output of them are same class yy(dict): pass ---ok class zz(kk) : fail ---error TypeError: Error when calling the me

今天早上我想出了一个奇怪的主意。我们知道,在python中,所有对象都是对象,包括类和函数

别问我为什么要这么做。这是一个关于python的实验。我知道它是从实例继承的

让我们试试:

kk=dict()
print dir(dict)
print dir(kk)
output of them are same

class yy(dict): pass ---ok
class zz(kk)  : fail ---error
TypeError: Error when calling the metaclass bases
dict expected at most 1 arguments, got 3
有人能详细解释我为什么会收到这个错误消息吗


再说一遍。如果可能,请解释python是如何输出此错误消息的?

这是因为您需要从
类型继承。
dict
是一个类型,
dict()
不是,它是dict的一个实例。
type
s类型是
type
,类型的所有实例都是
type
-它们的实例不是

>>> type(dict)
<class 'type'>
>>> type(dict())
<class 'dict'>
>>> isinstance(dict, type)
True
>>> isinstance(dict(), type)
False
>类型(dict)
>>>类型(dict())
>>>isinstance(命令,类型)
真的
>>>isinstance(dict(),类型)
假的

出现特定错误的原因与元类有关。任何类的元类都必须匹配或子类化每个类的元类(如果它是基类的话)(为了让继承的“is-a”规则起作用)。您尚未提供元类,因此python默认使用单一基类的类型。当基类是dict时,元类是type(默认值),并且一切正常。当基类是kk时,Python尝试使用dict作为元类——问题是,dict不是元类。错误显示“dict不遵循元类api”

zz
正在尝试从实例继承。对于
fail
上的
namererror
,它甚至还不够远。