python定义类时候加不加object区别
python 2.x
python2有经典类(旧式类)old-style(classic-style)
和新式类new-style
的区别
写法分别为:
1 | class A: |
继承object类的类就是新式类,目的就是让自己定义的类有更多的属性(因为本地只有python 3演示不了python 2不继承object类的效果,大概的输出:dir()只能输出'__doc__', '__module__'
两个属性,也就是说这个类的命名空间里面只有这两个属性可以操作)
python 3.x
python 3.x默认是继承object类的,不需要声明:
1 | #!/usr/bin/env python3 |
输出:
1 | Alice ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name'] |
为了养成良好的习惯,在定义类的时候,没有特定继承不妨也写出object类算是对自己的一个提示,该类的命名空间有哪些属性是可以操作的。
以上,完~