Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 797
Echoic Avatar asked Sep 14 '26 19:09

Echoic


1 Answers

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.

like image 115
Steve Jessop Avatar answered Sep 16 '26 09:09

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!