python的class(類)中的object是什麼意思?

 

上篇博文提到LEGB原則,其中最後一個B原則就是內置(built-in)命名空間, python

它會將python內部的__builtin__.py實例化的內容進行檢索什麼意思呢? 這裏先列出一段簡短的代碼。框架

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'


class Person(object):
    name = "zhengtong"


if __name__ == "__main__":
    x = Person()

 

 

經過這段代碼,當咱們實例化Person()這個類的時候,那x就是一個實例對象整個過程python除了建立Person這個類的命名空間以外(name=zhengtong加入到命名空間中),還會去執行__builtin__.py中的object類,並將object類中的全部方法傳承給Person(也就是說Person繼承了object的全部方法).ssh

 

回到主題上來,那寫object和不寫object有什麼區別?tornado

好的,再用代碼來理解它們的區別.ui

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'


class Person:
    """
    不帶object
    """
    name = "zhengtong"


class Animal(object):
    """
    帶有object
    """
    name = "chonghong"

if __name__ == "__main__":
    x = Person()
    print "Person", dir(x)

    y = Animal()
    print "Animal", dir(y)

 

運行結果spa

Person ['__doc__', '__module__', 'name']
Animal ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

 

 

Person類很明顯可以看出區別,不繼承object對象,只擁有了__doc__ , __module__ 和 本身定義的name變量也就是說這個類的命名空間只有三個對象能夠操做.code

Animal類繼承了object對象,擁有了好多可操做對象,這些都是類中的高級特性。orm

 

對於不太瞭解python類的同窗來講,這些高級特性基本上沒用處,可是對於那些要着手寫框架或者寫大型項目的高手來講,這些特性就比較有用了,好比說tornado裏面的異常捕獲時就有用到__class__來定位類的名稱,還有高度靈活傳參數的時候用到__dict__來完成.對象

 

最後須要說清楚的一點, 本文是基於python 2.7.10版本,實際上在python 3 中已經默認就幫你加載了object了(即使你沒有寫上object)。繼承

 

這裏附上一個表格用於區分python 2.x 和 python 3.x 中編寫一個class的時候帶上object和不帶上object的區別.

python 2.x python 2.x python 3.x python 3.x
不含object 含object 不含object 含object
__doc__ __doc__ __doc__ __doc__
__module__ __module__ __module__ __module__
say_hello say_hello say_hello say_hello
  __class__ __class__ __class__
  __delattr__ __delattr__ __delattr__
  __dict__ __dict__ __dict__
  __format__ __format__ __format__
  __getattribute__ __getattribute__ __getattribute__
  __hash__ __hash__ __hash__
  __init__ __init__ __init__
  __new__ __new__ __new__
  __reduce__ __reduce__ __reduce__
  __reduce_ex__ __reduce_ex__ __reduce_ex__
  __repr__ __repr__ __repr__
  __setattr__ __setattr__ __setattr__
  __sizeof__ __sizeof__ __sizeof__
  __str__ __str__ __str__
  __subclasshook__ __subclasshook__ __subclasshook__
  __weakref__ __weakref__ __weakref__
    __dir__ __dir__
    __eq__ __eq__
    __ge__ __ge__
    __gt__ __gt__
    __le__ __le__
    __lt__ __lt__
    __ne__ __ne__
相關文章
相關標籤/搜索