Difference between class declarations

2019-02-24 23:14发布

I see some similar questions about this topic, but i wish to be sure, so i am asking...

What is the difference between:

class MyClass:
    pass

and

class MyClass():
    pass

Also, is there a difference between these two:

class MyClass():
    pass

class MyClass(object):
    pass

标签: python class
3条回答
在下西门庆
2楼-- · 2019-02-24 23:50

Class declarations of the type class MyClass(object) are New Style classes on Python 2.x

Guido writes about some of the thinking that brought about the new classes in the History of Python

查看更多
Explosion°爆炸
3楼-- · 2019-02-24 23:55

There is no difference between the first two spellings.

In python 2.7, there is a huge difference between the latter two. Inheriting from object makes it a new-style class, changing the inheritance semantics and adding support for descriptors (@property, @classmethod, etc.). It's the default in Python 3.

New-style classes were introduced in Python 2.2 to unify types (such as int and list), and classes, and because several things change in backwards-incompatible ways, you need to 'opt in', explicitly inherit from object to enable the changes.

In Python 3, inheriting from object is no longer needed, classes are new-style, always.

查看更多
家丑人穷心不美
4楼-- · 2019-02-24 23:56

There is no difference between class MyClass and class MyClass(). The second question is dependent on your python version. On python3.x, there is no difference -- On python2.x, the latter (where you inherit from object) creates a new-style class rather than an old-style class. In python3.x, ALL classes are new-style. New style classes are preferred these days -- As such, I always make sure that my classes inherit from object.

查看更多
登录 后发表回答