Python - OOP - Object Oriented Programming - Part 2

In Python, every class is an instance of its metaclass, and every class has several built-in attributes that can be accessed through the class. Here are some of the most commonly used built-in class attributes:

__doc__: This attribute is used to access the docstring of a class. The docstring is a string that is placed at the beginning of a class or function and is used to document what the class or function does.

class MyClass:
    """This is a docstring for MyClass."""
    pass
print(MyClass.__doc__)  # Output: "This is a docstring for MyClass."

__name__: This attribute is used to access the name of a class.

class MyClass:
    pass
print(MyClass.__name__)  # Output: "MyClass"

__module__: This attribute is used to access the name of the module in which a class is defined.

# file name: mymodule.py
class MyClass:
    pass
print(MyClass.__module__) #Output: mymodule

__dict__: This attribute is used to access the dictionary that contains the namespace of a class.

class MyClass:
    a = 1
    b = 2
print(MyClass.__dict__) #Output: {'__module__': '__main__', 'a': 1, 'b': 2, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}

__bases__: This attribute is used to access the tuple that contains the base classes of a class.

class MyBaseClass:
    pass
class MyClass(MyBaseClass):
    pass
print(MyClass.__bases__) #Output: (<class '__main__.MyBaseClass'>,)

__class__: This attribute is a reference to the class of an instance.

class MyClass:
    pass
obj = MyClass()
print(obj.__class__)  # Output: <class '__main__.MyClass'>

__qualname__: This attribute is a string that holds the qualified name of the class.

class MyParentClass:
    class MyClass:
        pass
print(MyParentClass.MyClass.__qualname__)  # Output: "MyParentClass.MyClass"