您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python3中子类化类型vs对象

在Python3中子类化类型vs对象

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

# A type is an object
isinstance(int, object) # True

# But an object is not necessarily a type
isinstance(object(), type) # False

在Python中真正的是…

绝对一切,object是唯一的基本类型。

isinstance(1, object) # True
isinstance('Hello World', object) # True
isinstance(int, object) # True
isinstance(object, object) # True
isinstance(type, object) # True

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

type(1) # int
type('Hello World') # str
type(object) # type

那是相当明显的

isinstance(1, type) # False
isinstance(isinstance, type) # False
isinstance(int, type) # True

这是特定于该行为的,type对于任何其他类而言都是不可复制的。

type(type) # type

换句话说,type是Python中唯一的对象

type(type) is type # True

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

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

# This defines a class
class Foo(object):
    pass

# Its instances are not types
isinstance(Foo(), type) # False

# While this defines a Metaclass
class Bar(type):
    pass

# Its instances are types
MyClass = Bar('MyClass', (), {})

isinstance(MyClass, type) # True

# And it is a class
x = MyClass()

isinstance(x, MyClass) # True
python 2022/1/1 18:29:43 有210人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶