· Hakan Çelik · Python / Metaclass · 2 dk okuma

Understanding Python Classes

In Python, everything is an object and every object has a type — including primitives, functions, and classes themselves. type() and __class__ reveal this relationship.

Understanding Python Classes

In Python, everything is an object and every object has a type. This rule applies to primitives just as it applies to classes themselves. The type() function or the .__class__ attribute returns the type of any object; the two always produce the same result.

class Example:
	attr = 1

	def method(self):
		return "method"

print(f"{type(44)=}")              # type(44)=<class 'int'>
print(f"{type('hello')=}")         # type('hello')=<class 'str'>
print(f"{type(())=}")              # type(())=<class 'tuple'>
print(f"{type([])=}")              # type([])=<class 'list'>

print(f"{Example.__class__=}")     # <class 'type'>
print(f"{type(Example)=}")         # <class 'type'>
print(f"{type(type(type))=}")      # <class 'type'>

print(f"{Example().__class__=}")   # <class '__main__.Example'>

assert isinstance(Example, type)
assert isinstance(Example(), Example)

What Does the Output Tell Us?

The first four lines show what we expect: 44 is an int, 'hello' is a str.

The truly interesting part is the three lines in the middle:

  • Example.__class__<class 'type'> — the Example class itself is an instance of type. Classes are also objects; the type of these objects is type.
  • type(Example) → same result; using type() and .__class__ are equivalent.
  • type(type(type)) → still <class 'type'>type is its own metaclass; its type is itself.

The last line completes the picture: Example().__class__<class '__main__.Example'>. An instance created from a class returns its own class as its type — the same logic as with ordinary objects.

The assert Lines

assert isinstance(Example, type)    # Classes are instances of type
assert isinstance(Example(), Example)  # Instances are instances of their own class

These two rules are the foundation of Python’s object model. type sits at the top of the metaclass hierarchy; all classes — whether we are aware of it or not — are instances of type.

Back to Blog

Related Posts

View All Posts »
Run Methods Order In Python

Run Methods Order In Python

Python · 2 dk

Which method runs when in Python metaclasses? The execution order of __prepare__, __new__, __init__, and __call__ during class definition and instance creation.

namespace['attr'] = 1

namespace['attr'] = 1

Python · 2 dk

To see how Python truly processes a class statement: get a namespace with type.__prepare__, execute the body with exec, then build the class with type().