3

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?

JBernardo
  • 32,262
  • 10
  • 90
  • 115
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 1
    Your code is tagged `python-3.x` but it looks like `python-2.x` - `type(Foo)` returns `` in python 3+. – Holt Jan 08 '16 at 08:45
  • This is not directly related to this question, but good to know http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python – Aashish P Jan 08 '16 at 09:35

2 Answers2

2

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.

Community
  • 1
  • 1
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
0

In python classes are objects, ie classes are 'something which is like anything else' In your example,

class Foo():
    pass

x = Foo()

type(x)                     # Foo, x is a Foo
type(Foo)                   # type, Foo is a type

Foo ie a class you defined is not just a piece of code. It is an object which takes space in memory.

Foo == 1                    # Valid comparisson which evaluates to False
Bar = Foo                   # Assign new variable bar as Foo

Are valid operations.

>>> type(type(Foo))
<type 'type'>

type is a special kind of class (metaclass) and it's objects are classes which can create objects

Community
  • 1
  • 1
Vinayak Kaniyarakkal
  • 1,110
  • 17
  • 23