Python学习笔记 --- 解析 type 和 object

来源:互联网 发布:管家婆数据库在哪里 编辑:程序博客网 时间:2024/05/16 12:43
      规则
  1.若x是A的一个实例,且A是B的子类,那么x也是B的一个实例

  2.若B是M的实例,且A是B的子类,那么A也是M的一个实例


  首先type为object的子类,(A=type,B=object)

  >>> issubclass(type,object) True


  其次object是type的实例(x=object,A=type)

  >>> isinstance(object,type) True


  规则1得出object是object的实例(B=object,M=object)

  >>> isinstance(object,object) True


  规则2得出type是object的实例

  >>> isinstance(type,object) True


  同样可以得到type是type自己实例

  >>> isinstance(type,type) True


  PS:Python中所有类都是自己本身的子类

  >>> class A: ... pass ... >>> issubclass(A,A) True


继续:

有人会问这里既然相等为什么在定义的时候不用type 而是用object。

具体看这里代码实践:


class Foo(object):    passclass Foo1(type):    passprint len(dir(Foo))print "====================="print len(dir(Foo1))





这里可以看出type类比Object中的方法多,继续看

object含义为:

class object:    The most base type

type的含义为:


class type(object):    type(object) -> the object's type  type(name, bases, dict) -> a new type


因此可以比较出来定义时候继承基类object更为合适。


0 0
原创粉丝点击