type、object、class的关系

xiaoxiao2021-02-28  41

图中虚线代表实例关系,实线表示继承关系,从这个图中得出几点: 1、list、str、dict、tuple、type都继承了object,所以object是最顶层的基类 2、type是本身的对象(实例),object、list、str、dict、tuple都是type的对象,所以type创建了所有的对象 3、综合1、2可知,一切皆对象的同时又继承了object类,这就是python的灵活之处,Python的面向对象更加彻底

下面是验证的例子, #后面表示运行结果 type创建了所有的对象

a = 1 print(type(1)) # <class 'int'> print(type(int)) # <class 'type'>

type->int->1 即type类生成int,int类生成了1

s = 'abc' print(type(s)) # <class 'str'> print(type(str)) # <class 'type'>

type->str->’abc’ 所以type可以生成class(类), class生成obj(对象)

以上是内置类,现在我们自己创建来看下

class Student: pass stu = Student() print(type(stu)) # <class '__main__.Student'> print(type(Student)) # <class 'type'>

结果和上面的情况一样,type->Student->stu

class Student: pass #Student继承了最顶层的object同时Student又是type的对象 Student.__bases__ # <class 'object',> print(type(Student)) # <class 'type'> #type是自身的对象,objecttype的对象 print(type(type)) # <class 'type'> print(type(object)) # <class 'type'> #type继承了object类,最顶层的object的基类为空 print(type.__bases__) # <class 'object'> print(object.__bases__) # ()
转载请注明原文地址: https://www.6miu.com/read-2621113.html

最新回复(0)