Built-in class attributes
Built-in class attributes
In Python, there are several built-in class attributes that provide information about the class and its instances. These attributes can be accessed using the dot notation. Here are some commonly used built-in class attributes:
### `__doc__`
This attribute contains the docstring, which is a string that provides documentation for the class. It is created by placing a string literal as the first statement in the class definition.
```python
class MyClass:
"""This is a docstring."""
pass
print(MyClass.__doc__) # Output: This is a docstring.
```
### `__name__`
This attribute contains the name of the class as a string.
```python
class MyClass:
pass
print(MyClass.__name__) # Output: MyClass
```
### `__module__`
This attribute contains the name of the module in which the class is defined.
```python
# Module: mymodule.py
class MyClass:
pass
print(MyClass.__module__) # Output: mymodule
```
### `__bases__`
This attribute contains a tuple of the base classes of the class.
```python
class Parent:
pass
class Child(Parent):
pass
print(Child.__bases__) # Output: (<class '__main__.Parent'>,)
```
### `__dict__`
This attribute contains a dictionary containing the namespace of the class, i.e., the mapping of attribute names to their values.
```python
class MyClass:
attribute = 42
print(MyClass.__dict__) # Output: {'__module__': '__main__', 'attribute': 42, ...}
```
### `__class__`
This attribute is an instance's class. It is equivalent to accessing the class through the instance.
```python
class MyClass:
pass
obj = MyClass()
print(obj.__class__) # Output: <class '__main__.MyClass'>
```
These built-in class attributes provide introspection capabilities, allowing you to inspect and retrieve information about classes and their instances at runtime. They are particularly useful for debugging, documentation, and metaprogramming.
Comments
Post a Comment