Echoic
Echoic

Reputation: 250

Python classes explained

Why does Python see these classes as different data types?

>>> class A:
...    pass
...
>>> class B(object):
...     pass
...
>>> a = A()
>>> b = B()
>>> type(A)
<type 'classobj'>
>>> type(B)
<type 'type'>
>>> type(a)
<type 'instance'>
>>> type(b)
<class '__main__.B'>

I'm pretty new. So I don't really understand why it sees all of this as different data types. They are both classes so it seems as though they should be the same.

Upvotes: 3

Views: 882

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279385

You're using Python 2.

Python 2 allows classes that don't inherit from object, which was added in version 2.2. They behave differently from "new-style classes" in a few ways, and you've found a couple.

There's no reason for the different behaviour other than to retain backward-compatibility, that is to ensure that code written for old-style classes continues to work in new releases of Python 2.

Python 3 is not backward-compatible and does not have old-style classes. If you wrote the same code in Python 3, then A would inherit from object even though you don't say so explicitly.

Upvotes: 7

Related Questions