Attributes in Python

Introduction
Any OOPs language has behaviour and characteristics properties. In Python, attributes are the same as characteristic properties in any other language. With the methods dir() attributes of python can be accessed. An example is demonstrated below:
Code
Output
Types of attributes
Attributes can be of two types:
- Class attributes
- Instance attributes
Class attributes
In python, attributes that are defined out of the method but inside the python class object are known as class attributes. They belong to the class and can be accessed by class and instance objects.
Syntax
Code
Output
Instance attributes
The attributes that are defined inside the init method are called instance attributes. Using an instance of the class, we can access these attributes. They belong to an instance of objects.
Syntax
Code
Output
Uses of class attributes
For many different, we can use Class attributes. Some of them are mentioned below:
For creating a constant value variable
Across all the instances listing the objects
to provide a default variable
Across all the instances of the class, class attributes are initialized. So we can create use class attributes to create constant value variables in the class and these variables can be used in the functions. The class attribute also takes less time to initialize and has low memory space.
Code
Output
Explanation
Now in the above code, we created a variable named “pi” and it stores a constant value. Here, pi is a class attribute.
- We created a method that will calculate the area.
- And then we created an object of the class.
- And then at last we print the area of the circle.
In a case where we want to access some properties of all instances of the class. When we access properties by calling each object it consumes very much time. By using class attributes, we can arrange all the instances of the class inside a single variable.
Namespaces in attributes
- In python, a namespace is a dictionary, that allows us to store the key as an object and the value as an attribute. Now for this case, it can be divided into two parts:
- Object Namespace
- Class Namespace
- Whenever a class instance tries to access any of the attributes, it will first search in the object namespace and then afterwards in the class namespace. The instance attribute is more before class attributes. It will be time-consuming when we access class attributes by the instance of the class.
- Whenever a class try to access any of its attributes, it first searches in the class attribute and if otherwise throws an error.