Python Mastery – From Basics to Brilliance / Object-Oriented Programming (OOP)

@property

🏷️ @property

@property allows us to access a method like an attribute, without using ().

It is commonly used for encapsulation and controlled access to instance variables.


πŸ”Ή Without @property

class Student:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

student = Student("Codeveda")

print(student.get_name()) #Codeveda

We have to use () because get_name() is a method.

πŸ”Ή With @property

class Student:
    def __init__(self, name):
        self.name = name
    @property
    def name_upper(self):
        return self.name.upper()
student = Student("Codeveda")
print(student.name_upper) #Codeveda

Notice: student.name_upper instead of: student.name_upper()

The method behaves like an attribute.


πŸ” Property with Getter & Setter

@property can also control how an attribute is read and modified.

class Student:
    def __init__(self, age):
        self._age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value >= 0:
            self._age = value

student = Student(20)

print(student.age) #20

student.age = 21
print(student.age) #21

Here: @property is for Get/read the value and @age.setter is for Set/change the value

Use @property when you want attribute-like access while still having control over how the value is calculated or validated.