先来看一段小代码:
定义了两个类,Cat不带object,而Dog带有参数object,会不会有差别呢?
print出来其实结果是一模一样的:
Cat ['__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']
Dog ['__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']
为什么会这样呢,因为ython 3 中已经默认就帮你加载了object了(即便你没有写上object)。
但是大家一定要注意,如果项目是用python2写的,不继承object对象,只拥有了__doc__ , __module__ 和 自己定义的name变量, 也就是说这个类的命名空间只有三个对象可以操作。
例子如下:
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']
本人踩过的一个小坑,在此总结。