先看两段代码
Python 2.7.5
# -*- coding: utf-8 -*- # 旧式类 class Foo(): pass foo = Foo() print(foo.__class__) print(type(foo)) # __main__.Foo # <type 'instance'> # obj.__class__就表示该类,但type(obj)始终是instance类型 # 新式类 class NewFoo(object): pass new_foo = NewFoo() print(new_foo.__class__) print(type(new_foo)) # <class '__main__.NewFoo'> # <class '__main__.NewFoo'> # type(obj)则与obj.__class__相同
Python 3.6.5
# -*- coding: utf-8 -*-
class Foo():
pass
foo = Foo()
print(foo.__class__)
print(type(foo))
# <class '__main__.Foo'>
# <class '__main__.Foo'>
class NewFoo(object):
pass
new_foo = NewFoo()
print(new_foo.__class__)
print(type(new_foo))
# <class '__main__.NewFoo'>
# <class '__main__.NewFoo'>
小结
新式类: 类(class)和类型(type)相同
旧式类: 类(class)和类型(type)不同
所以,为了兼容py2 和 py3,最好的写法是继承object:
class Foo(object):
pass
参考
</div>