那寫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__ |
原文地址:https://blog.csdn.net/DeepOscar/article/details/80947155