13

example #1:

class Person(object):
    pass

example #2:

class Person:
    pass

What does the object declaration do? Should you use it? I have a bunch of programs with both of them and don't know the difference it is making. If anyone can explain this concept please.

Paul Manta
  • 30,618
  • 31
  • 128
  • 208
Paxwell
  • 748
  • 10
  • 18

2 Answers2

16

In Python2, declaring object as the base class makes the class a new-style class. Otherwise, it is a "classic" class. Among the differences are that

  • Properties only work with new-style classes

  • new-style classes have the mro method

  • new-style classes have many attributes that classic classes lack

    In [288]: class Foo: pass
    In [289]: dir(Foo) 
    Out[289]: ['__doc__', '__module__']
    
    In [290]: class Bar(object): pass
    In [291]: dir(Bar) 
    Out[291]:  ['__class__',  '__delattr__',     '__dict__',  '__doc__',  '__format__',  '__getattribute__',     '__hash__',  '__init__',  '__module__',  '__new__',  '__reduce__',     '__reduce_ex__',  '__repr__',  '__setattr__',  '__sizeof__',     '__str__',  '__subclasshook__',  '__weakref__']
    

Classic classes are retained in Python2 only for backwards compatibility. All custom classes you define should be made new-style.

In Python3, all classes are new-style, so it need not be explicitly declared there.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • +1 to this! As an aside: AFAIK there are no drawbacks to using new-style classes, so I feel that you should use them all of the time, without exception. Old-style classes only exist, as the name implies, for backwards compatibility (which is why they were finally removed in Python 3.0). – Andrew Gorcester Nov 16 '12 at 21:10
  • Thank you for providing more than one is old, one new. I appreciate when people take the time to help others learn. – Paxwell Nov 16 '12 at 21:20
  • I can think of one occasional advantage of oldstyle classes: special method lookup can be on the instance. E.g. `a = oldstyle(); a.__add__ = lambda *args: 'changed'` will work but the equivalent with a newstyle object won't. Maybe once or twice I've wished this would work without creating a new class instead, but that's it, and mostly it was a sign my structures needed rethinking. – DSM Nov 16 '12 at 21:23
0

In Python 2, the object makes it a "new-style class". The details of what this means aren't too important, but the bottom line is you should always use it or some things might not work right.

In Python 3, everything is always a new-style class, so you don't need to use object there.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384