1

In Python 2:

>>> class A:
...  pass
... 
>>> A.__new__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute '__new__'
>>> class A(object):
...  pass
... 
>>> A.__new__
<built-in method __new__ of type object at 0x1062fe2a0>

Conclusion: object contains __new__ and subclasses inherit the method.

in Python 3:

>>> class A:
...  pass
... 
>>> A.__new__
<built-in method __new__ of type object at 0x100229940>

__new__ is a defined method in our class, without any inheritance. How does this work? Where does __new__ "come from"?

Sahand
  • 7,980
  • 23
  • 69
  • 137

2 Answers2

5

In Python 3, if you create a class without adding a parent class it automatically inherits from object. You can't create old style classes anymore like Python 2.

Example:

class A: # gets defaulted to class A(object):
    pass
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Mohd
  • 5,523
  • 7
  • 19
  • 30
1

All classes in Python3 are subclasses of object as you can see from the mro:

>>> class A: pass
... 
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)

class A(object) is still done in some Python 3 code to maintain backward compatibility with Python 2.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139