美文网首页
1-2 type、object和class的关系

1-2 type、object和class的关系

作者: xgnb | 来源:发表于2019-03-10 21:42 被阅读0次

通过这3者的关系去理解python的一切皆对象。

type-我们知道type有两种用法,
(1)通过type来生成一个类 。(后面学到元类编程的时候再回来补坑)
(2)通过type来返回一个对象的类型。
请看下面:

type生万物.png
通过这个例子我们可以知道type->int->1,由type生成了我们的int再又int生成了我们的1,同理对于字符串、常用数据结构列表...也相同。
归结:type->class->->obj,type是用来生成类的
class Student:
    pass

class MyStudent(Student):
    pass


stu = Student()
print(type(stu))  #  class 生成实例 obj
print(type(Student))  # type 生成 class
print(MyStudent.__bases__)  # MyStudent的基类为Student
print(Student.__bases__)  # Student没有继承任何类,默认继承object基类
print(int.__bases__)  # 同理,默认继承object
print(str.__bases__)  # 同理,默认继承object
print(type.__bases__)  # type 也是类,继承object基类
print(object.__bases__)  # object 最顶的基类,不继承任何基类
print(type(object))  # type 生成 class
output1.png relationship.jpg

相关文章

网友评论

      本文标题:1-2 type、object和class的关系

      本文链接:https://www.haomeiwen.com/subject/adxvcqtx.html