开发者

What's the difference between 'class A:' and 'class A(object):' in Python?

开发者 https://www.devze.com 2023-02-01 20:14 出处:网络
What\'s the difference between class A: pass and class B(object): pass ? For some reason, in methods I c开发者_开发知识库an\'t use super(A, self) but super(B, self) works great. I guess there\'s

What's the difference between

class A:
    pass

and

class B(object):
    pass

? For some reason, in methods I c开发者_开发知识库an't use super(A, self) but super(B, self) works great. I guess there's no such peculiarity in Py3k :)


The first is an old style class. The second is a new-style class. See http://docs.python.org/tutorial/classes.html#multiple-inheritance for a good discussion of the difference. super() only works with new-style classes. http://docs.python.org/library/functions.html#super


In 2.x, the latter creates a new-style class. In 3.x, both have the same effect since old-style classes have been removed.


Class B is a new style class http://www.python.org/doc/newstyle/


As already said the second case creates a new-style class, while the first one creates an old-style class(deprecated!).

New-style classes where created to remove the limitation of the old-styles: old-style classes could not inherit from built-in types. With new-style classes you can inherit from built-in types; in fact all built-in types derive from "object":

>>> list.__mro__
(<type 'list'>, <type 'object'>)
0

精彩评论

暂无评论...
验证码 换一张
取 消