Home > Enterprise >  Class object and class type in Python
Class object and class type in Python

Time:07-02

I am new to Python and I have a question about OOP. So, when we create a class we write "object" in parentheses. For example,

class My(object):

I have read somewhere that this means that the class inherits from the object class in Python. But I also have read that every class we create is an instance of the type class. So my question is the object class the same as the type class and, if yes, why, when ask Python to print the type of a class, it returns <class 'type'> and not <class 'object'>. Also, why can’t we write

class My(type):

if the object class and the type class are the same?

CodePudding user response:

There are two relationships here: instance of and subtype of. For a non-programming analogy, you can think about the difference like this. A particular apple sitting on a desk is an instance of "apple". It's an example of an apple, that particular one. On the other hand, "apple" as a concept is a subtype of "fruit". Every apple is a fruit. It wouldn't be accurate to say that the particular apple sitting on your desk is a subtype of anything, because it's a specific one. And it wouldn't make sense to say the concept of "apple" is an instance of "fruit", because it's not.

Every class you define in Python is a subtype of object, which is the type of all types. The class itself is also an object in Python, and its type is type. The latter can be used to do some clever metaprogramming, but that's advanced Python that you probably don't need to be messing with at this stage.

class Foo(object):
  pass

assert isinstance(Foo, type) # Foo is a type
assert issubclass(Foo, object) # Foo is a subclass of object
assert isinstance(Foo, object) # Every type (and everything in Python) is an object
assert isinstance(Foo(), Foo) # A specific foo is a Foo
assert isinstance(Foo(), object) # A specific foo is an object

For right now, as you're learning Python, it's pretty safe to just forget type exists. It's fancy and complicated and used for some really sophisticated metaprogramming tricks. For now, just use object and assume classes are some magical thing, and learn how to use them. You can learn the gritty details of how they work once you have a firm foundation.

  • Related