Updated April 14, 2023
Introduction to Python Class Attributes
An attribute of class means these are the terms used for describing the properties or fields or data members or class members of the class. Attribute simply means the data member of an object. In Python, the class attribute is an attribute of the class that belongs to the class itself, which means it is the class’s attribute rather than an attribute of an instance of a class. The Python class attributes will be shared by all the instances where instance attributes are not shared between instances. These class attributes are usually defined in the class body parts at the top for better understanding.
Working of the Class Attribute with examples
An attribute is a changeable property or any characteristics of any component or program, or class that can set to different values. For example: In general, the attribute for humans can be hair, the color of the face, etc.
So let us have an example of how the class attributes are created in the below example:
Example #1
Code:
class classwithattribute:
count = 0
print (count)
def increment(self):
classwithattribute.count += 1
c1 = classwithattribute()
c1.increment()
print (c1.count)
c2 = classwithattribute()
c2.increment()
print (c2.count)
print (classwithattribute.count)
Output:
In the above example, we have a class named “classwithattribute” and class attribute as “count”, which is initialized to value “0” then we are writing a function to increase the value of the count attribute by 1, and this is done in a function called “increment”. Then we create a variable of the class, and then we call the function with the class variable “c1”.
In Python, attributes which are used to implement access controls of classes. There are several built-in methods and functions to access these attributes of the class.
- getattr(): this is used to get the attribute so that it can get to access these attributes of the object.
- hasattr(): this function is used to know whether the attributes are present in the class or not.
- setattr(): this method is used to assign the values to the attribute, and this method also creates the attribute and then sets the attribute if the attributes are not present.
- delattr(): this function is used for deleting the attribute created for the class, and it will give an error if trying to access the same attribute after deleting it.
Let us consider an example to demonstrate all the above built-in methods that are used to access the class attributes.
Example #2
Code:
class student:
name='Rob'
age='15'
def display(self):
print (self.name)
print (self.age)
s1 = student()
print("This will display the attribute value")
print (getattr(s1,'name'))
print ("\n")
print("This will check if the attribute is present or not")
print (hasattr(s1,'name'))
print ("\n")
print("This will set new attribute with its value")
setattr(s1,'weight',30)
print ("\n")
print (getattr(s1,'weight'))
print ("\n")
print("This will delete the attribut specified")
delattr(student,'age')
print ("\n")
print("This will give error as it is already deleted")
print (getattr(s1,'age'))
Output:
In the above example, we have written code to demonstrate the above-accessing methods for class attributes. In the above, we have created a class “student” with attributes “name”, “age” to display these details, we have a “display” function, so this class variable “s1” is used in all the methods. In getattr(s1, name), we are asking to fetch the attribute value of attribute “name” as Rob, which is assigned at the beginning of attribute creation. Similarly, hasattr(s1, “name”) searches for the “name” attribute in the class “student” if it exists, then returns true else false. Then setattr(s1, “weight”) this function will create a new attribute if not there or else it will assign the value to the attribute. And lastly, the delattr (student,’ age’) this function will delete the attribute “age” from the class “student”. This attribute will no more be accessible after deleting the attribute.
As the class attributes can be accessed from one class to another class. In this section, we will see accessing attributes and methods of the class in another class. To access the attributes or methods of one class in any other class, we have to bypass the object of the class to another class. Let us consider an example to demonstrate this concept:
Example #3
Code:
class firstclass():
def __init__(self):
self.a1 = 1
self.a2 = 2
def methodfirst(self):
self.a1 = self.a1 + self.a2
return self.a1
class secondclass(firstclass):
def __init__(self, class_first):
self.a1 = class_first.a1
self.a2 = class_first.a2
object1 = firstclass()
summation = object1.methodfirst()
print (summation)
object2 = secondclass(object1)
print (object2.a1)
print (object2.a2)
Output:
In the above program, there are two classes defined “firstclass” and “secondclass”, in the “firstclass” we have defined the function of addition of two numbers which are declared as attributes in “firstclass”, and then this “firstclass” is passed to “secondclass” so the objects of both classes are created, and it returns the summation of two numbers.
When use Python Class Attributes?
Let us see when we can use Python class attributes:
- So we know that class attributes can be accessed within the class and in another class, so it is often used to store some constants as we did in the above program to access the class attribute of one class in another class.
- Sometimes the class attributes are used to define some default values. If one class has the attribute to hold some limit value or some bounded list, we need to create an instance by assigning some instance’s limit attribute.
Conclusion
In Python, many think that class attributes concept is a bit tricky, so they are not used much, but we should take care of how and when to use these. So, in general, class attributes and class attributes are nothing but simple properties of the class they define. There are many different methods and functions to access the class attributes as well as there is an option in which class attributes of one class can be accessed in other class; rather, instances can access only within the class.
Recommended Articles
We hope that this EDUCBA information on “Python Class Attributes” was beneficial to you. You can view EDUCBA’s recommended articles for more information.