__class__Easy Examples

Reference to the class that an instance belongs to

Accessing __class__

How to access and use __class__.

python
# __class__ refers to an object's type
x = 42
print(x.__class__)
print(x.__class__.__name__)

class Dog:
    pass

d = Dog()
print(d.__class__)

__class__ is a special attribute that reference to the class that an instance belongs to.

__class__ in practice

Using __class__ in everyday code.

python
# More __class__ examples
print("__class__ is a special Python attribute")

# Every object has certain dunder attributes
obj = object()
attrs = [a for a in dir(obj) if a.startswith("__")]
print(f"object has {len(attrs)} dunder attributes")

Understanding __class__ helps you introspect and debug Python objects.

Want to try these examples interactively?

Open Easy Playground