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


那寫object和不寫object有什么區別?

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

  1.  
    # -.- coding:utf-8 -.-
  2.  
    # __author__ = 'zhengtong'
  3.  
     
  4.  
     
  5.  
    class Person:
  6.  
         """
  7.  
        不帶object
  8.  
        """
  9.  
        name =  "zhengtong"
  10.  
     
  11.  
     
  12.  
    class Animal(object):
  13.  
         """
  14.  
        帶有object
  15.  
        """
  16.  
        name =  "chonghong"
  17.  
     
  18.  
    if __name__ == "__main__":
  19.  
        x = Person()
  20.  
         print "Person", dir(x)
  21.  
     
  22.  
        y = Animal()
  23.  
         print "Animal", dir(y)

運行結果

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

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

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

 

對於不太了解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__

 

 

原文地址:https://blog.csdn.net/DeepOscar/article/details/80947155

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM