Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `type()` `__class__` and `__bases__` in Python?

Tags:

python

types

oop

I tried this in Python's REPL:

>>> class Foo:
...  def f():{}
... 
>>> 
>>> type(Foo)
<type 'classobj'>
>>> Foo.__bases__
()
>>> type(type(Foo))
<type 'type'>
>>> type(Foo).__bases__
(<type 'object'>,)

However, I still can't figure out what "data type" means in OOP exactly.

In Python, I know that an instance can get its class by .__class__ and a class can get its parent class by .__bases__. This seems easy to understand.

But what does the the type of a "Class", or TypeObject, mean? And what does the type of a Type Object mean? What does the __bases__ of a Type Object mean? What is the difference between type and class in Python?

This looks a bit confusing to me.. Does anyone have ideas about this?

like image 476
Hanfei Sun Avatar asked Sep 08 '26 09:09

Hanfei Sun


1 Answers

The key to understanding is recognizing that everything in python is an object. Also, technically object isn't a keyword, it's a global built-in.

This answer is perhaps the best explanation I've ever seen on the topic. I highly recommend reading the entire post. It talks a lot about metaclasses, and type is very much tied to metaclasses.

Essentially, the type of a Class is a MetaClass. And in the same way that all new-style classes in python inherit from object, all metaclasses inherit from type. It's a bit confusing because the type global in python is used for two different purposes. It's a metaclass and a function that returns the type of an object.

A very simple way to think of it is that metaclasses create classes, in the same way that Classes create instances.

like image 145
Brendan Abel Avatar answered Sep 10 '26 22:09

Brendan Abel



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!