Difference between class declarations

I see some similar questions on this topic, but I want to be sure, so I ask ...

What's the difference between:

class MyClass:
    pass

      

and

class MyClass():
    pass

      

Also, is there a difference between the two:

class MyClass():
    pass

class MyClass(object):
    pass

      

+3


source to share


3 answers


There is no difference between the first two spellings.

In python 2.7, there is a huge difference between the latter two. Inheritance of object

making it a new-style class , changing the semantics of inheritance and adding support for tags ( @property

, @classmethod

, etc.). This is the default in Python 3.



Python 2.2 introduced new style classes to unify types (eg, int

and list

) and classes, and because several things change in the opposite direction are incompatible, you need to "select" explicitly inherit from object

to enable changes.

In Python 3, inheritance from is object

no longer required, classes are always new.

+5


source


There is no difference between class MyClass

and class MyClass()

. The second question depends on your python version. There is no difference on python3.x - on python2.x the latter (where you inherit from object

) creates a new style class , not an old style. In python3.x, ALL classes are new. New style classes are preferred these days. This way, I always make sure my classes inherit from the object.



+7


source


Type Class Declaration class MyClass(object)

New Style Classes in Python 2.x

Guido writes about some of the thoughts that sparked new classes in Python History

+3


source







All Articles