在Python3中子类化类型vs对象

在Python3中子类化类型vs对象,第1张

在Python3中子类化类型vs对象

object
和之间没有交叉继承关系
type
。实际上,交叉继承是不可能的。

# A type is an objectisinstance(int, object) # True# But an object is not necessarily a typeisinstance(object(), type) # False

在Python中真正的是…

一切 都是 对象

绝对一切,

object
是唯一的基本类型。

isinstance(1, object) # Trueisinstance('Hello World', object) # Trueisinstance(int, object) # Trueisinstance(object, object) # Trueisinstance(type, object) # True
一切 都有 一种

一切都有内置或用户定义的类型,可以使用来获得此类型

type

type(1) # inttype('Hello World') # strtype(object) # type
并非一切都是一种类型

那是相当明显的

isinstance(1, type) # Falseisinstance(isinstance, type) # Falseisinstance(int, type) # True
type
是自己的类型

这是特定于该行为的,

type
对于任何其他类而言都是不可复制的。

type(type) # type

换句话说,

type
是Python中唯一的对象

type(type) is type # True# While...type(object) is object # False

这是因为

type
是唯一的内置元类。元类只是一个类,但它的实例本身也是类。所以在你的例子中

# This defines a classclass Foo(object):    pass# Its instances are not typesisinstance(Foo(), type) # False# While this defines a metaclassclass Bar(type):    pass# Its instances are typesMyClass = Bar('MyClass', (), {})isinstance(MyClass, type) # True# And it is a classx = MyClass()isinstance(x, MyClass) # True


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674482.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存