1-2 type、object和class的关系
2019-03-10 本文已影响0人
xgnb
通过这3者的关系去理解python的一切皆对象。
type-我们知道type有两种用法,
(1)通过type来生成一个类 。(后面学到元类编程的时候再回来补坑)
(2)通过type来返回一个对象的类型。
请看下面:
![](https://img.haomeiwen.com/i11797926/317376ff8bf485ec.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
![](https://img.haomeiwen.com/i11797926/b78fb5c48f18d285.png)
![](https://img.haomeiwen.com/i11797926/a9b0f3941f568d86.jpg)