Read Only Properties in Python
Prerequisites: Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. To put it in simple words, let us assume a class Student, a student can have many properties such as Name, Course, Student’s ID, etc. Now let us assume we have a Student named Anita pursuing MBA, Anita is an object of class Student.
Example:
class student: def __init__(self, name, course): self.name = name self.course = course def studentid(self): return "student's identification number is \ {}{}".format(self.name, self.course) student1 = student("Anita", "MBA")print(student1.studentid()) |
Output:
student's identification number is AnitaMBA
Now, We want to access student id as a property and not as a method. For this all required is to add @property decorator before the method.
Example:
class student: def __init__(self, name, course): self.name = name self.course = course @property def studentid(self): return "student's identification number is \ {}{}".format(self.name, self.course) student1 = student("Anita", "MBA")print(student1.studentid) |
Output:
student's identification number is AnitaMBA
A Read-Only-Property is a property decorator without a setter. The student id here is a read-only-property since it doesn’t have a setter. In general terms, it means that the value is not changeable. To understand let’s take one more example:
Example:
class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking @property def salary(self): self.salary = 50000 amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsworking, amit.salary) |
Output:
Traceback (most recent call last):
File “/home/e029e0b9ccad85905e22dd5a91943897.py”, line 14, in
amit.salary = 10000
AttributeError: can’t set attribute
To fix this one setter is to be added in this code. After doing this, it will no longer be a read-only-property.
Example:
class employee: def __init__(self, basesalary, yearsofworking): self.basesalary = basesalary self.yearsofworking = yearsofworking self._salary = 0 @property def salary(self): return self._salary @salary.setter def salary(self, salary): self._salary = salary amit = employee(20000, 5)amit.salary = 10000print(amit.basesalary, amit.yearsofworking, amit.salary) |
Output:
20000 5 10000





Please Login to comment...