8

some time i see some classes defined as subclass of object class, as

class my_class(object):
    pass

how is if different from the simple definition as

class my_class():
    pass
Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106

5 Answers5

8

This syntax declares a new-style class.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 3
    +∞: Oh look the question's already answered in the documentation. I wish folks would read more and ask less. – S.Lott Mar 10 '11 at 15:45
4

The first one is a 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__']
gruszczy
  • 40,948
  • 31
  • 128
  • 181
3

For Python 3.x, there is no difference. In Python 2.x, deriving from object makes a class new-style, while providing no base classes will give you an old-style class.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

For new-style classes in Python 2.x, you MUST explicitly inherit from object. Not declaring that a class inherit from object gives you an old-style class. In Python 3.x, explicitly inheriting from object is no longer required, so you can just declare in Python 3.x with Python 2.x old-style class syntax class Klass: pass and get back a new-style (or just a class) class.

Y.H Wong
  • 7,151
  • 3
  • 33
  • 35
2

This is the "NEW" Style, and your question is similar to Python class inherits object

Community
  • 1
  • 1
kamal
  • 9,637
  • 30
  • 101
  • 168