python中為什麼要繼承object類

2021-08-27 07:52:53 字數 3452 閱讀 3770

這裡先列出一段簡短的**。

# -.- 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的所有方法).

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

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

# -.- 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)

執行結果

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變數, 也就是說這個類的命名空間只有三個物件可以操作.

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__

Python 為什麼要繼承 object 類?

寫東西的時候剛好遇到這個問題,回答一波 繼承 object 類的是新式類,不繼承 object 類的是經典類,在 python 2.7 裡面新式類和經典類在多繼承方面會有差異 classa deffoo self print called a.foo classb a pass classc a d...

Python 為什麼要繼承 object 類?

繼承 object 類的是新式類,不繼承 object 類的是經典類,在 python 2.7 裡面新式類和經典類在多繼承方面會有差異 classa deffoo self print called a.foo class b a pass class c a def foo self print ...

為什麼要繼承Serializable

最重要的兩個原因是 1 將物件的狀態儲存在儲存 中以便可以在以後重新建立出完全相同的副本 2 按值將物件從乙個應用程式域傳送至另乙個應用程式域。實現serializable介面的作用是就是可以把物件存到位元組流,然後可以恢復。所以你想如果你的物件沒實現序列化怎麼才能進行網路傳輸呢,要網路傳輸就得轉為...