在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      

posted on 2019-03-26 18:07  布织布织  阅读(14694)  评论(1编辑  收藏  举报