python定義類時,class()與class(object)的區別


在python2中,class(object)定義時,class繼承了object()的屬性;

在python3中,class()默認繼承了object();

 

為什么要繼承object類呢?目的是便於統一操作。繼承object類是為了讓自己定義的類擁有更多的屬性。

 

python2中需要寫為以下形式:

1 def class(object):

 

舉例如下:

 1 class Person:  2     """
 3  不帶object  4     """
 5     name = "zhengtong"
 6 
 7 
 8 class Animal(object):  9     """
10  帶有object 11     """
12     name = "chonghong"
13 
14 if __name__ == "__main__": 15     x = Person() 16     print "Person", dir(x) 17 
18     y = Animal() 19     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,擁有很多可操作的對象,這些都是類中的高級特性。

 

(參考自:

    https://blog.csdn.net/w571523631/article/details/55099385

    https://blog.csdn.net/yinboxu/article/details/79852772      


免責聲明!

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