Python class definition

for a while I see some classes defined as a subclass of an object class, and

class my_class(object):
    pass

how different from a simple definition of how

class my_class():
    pass
+3
source share
5 answers

This syntax declares a new style class .

+7
source

The first is the new style class, and the second is the old style class.

EDIT

In [1]: class A:
   ...:     pass
   ...: 

In [2]: class B(object):
   ...:     pass
   ...: 

In [3]: a = A()

In [4]: b = B()

In [5]: dir(a)
Out[5]: ['__doc__', '__module__']

In [6]: dir(b)
Out[6]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
+4
source

Python 3.x . Python 2.x object , .

+3

For new-style classes in Python 2.x, you SHOULD explicitly inherit from object. Without declaring that the class inherits from object, you get an old-style class. In Python 3.x, it is not explicitly inherited from object, so you can simply declare it in Python 3.x with Python 2.x old-style style syntax class Klass: passand return a new style (or just a class).

+3
source

This is a "NEW" style, and your question is similar. Python class inherits from object

+2
source

All Articles