How to make a class property in python

Python is an object-oriented programming language that is based on an object. An object is basically a collection of variable and functions or methods which are performed on that variable. A class acts like a blueprint for objects. In this article, we’ll discuss how to make a class property in Python. The property() method is used to define the properties of a certain class. It uses the setter, getter, and delete features.

Python programming language uses a built-in property decorator that uses the getter and setters techniques. If you want to learn more about Python Programming, visit Python Programming Tutorials.

Before diving into the details, let’s first see why we need a property() decorator. There are some situations where you need to implement some conditions on the class attributes. Suppose you have a class student consisting of two attributes: name and age. As you know that age cannot be negative. There are two ways by which you can implement this condition on age attribute. The first one is to check the age of each object using if else condition before assigning it to the object. But, in this case, you have to check this condition every time, a new object is created. Another way is to use getter and setter methods to add a condition around getting or setting a value.

class Student:
    def __init__(self, name, age): = name;

    def set_age(self, age):
        if age <= 0:
            raise ValueError('The age must be positive')
        self._age = age

    def get_age(self):
        return self._age

#create an object s1
s1 = Student('John',23);
print("The age of " + + " is " + str(s1.get_age()));
The age of John is 23
#create another object s2
s2 = Student('Elizabeth',-9);
ValueError: The age must be positive

Class property in python (@property)

The property() decorator allows access of private attributes of a class using getter and setter functions. You can access or change them using their name. The property decorator has three methods: getter, setter, and delete, and returns a property object. The syntax of the property function is:

property(fget, fset, fdel, doc)

It takes four arguments as input as shown in the syntax

  • fget(Optional): Function for getting an attribute value.
  • fset(Optional): Function for setting an attribute value. 
  • fdel(Optional): Function for deleting an attribute value. 
  • doc(Optional): creates a docstring for the attribute.
class Student:
    def __init__(self):

    # a getter function
    def age(self):
      return self._age
    # a setter function
    def age(self, a):
      if a <= 0:
        raise ValueError('The age must be positive')
      self._age = a
s1 = Student()
print("The age of Student is " + str(s1.age));
The age of Student is 21

Leave a Comment

Your email address will not be published. Required fields are marked *