Home Tutorials Python OOP Concepts Setter Method with @property
Setter Method with @property

Setter Method with @property


37. Setter Method with @property

A setter works with @property to update values using attribute-style syntax. This is useful when validation is needed before assignment.

Syntax

@name.setter
def name(self, value):
    self._name = value

Example

class Student:
    def __init__(self, marks):
        self._marks = marks
        
    @property
    def marks(self):
        return self._marks
        
    @marks.setter
    def marks(self, value):
        if value >= 0:
            self._marks = value

s = Student(80)
s.marks = 90
print(s.marks)

Output

90
Example

🏋️ Test Yourself With Exercises

Take our quiz on Setter Method with @property to test your knowledge.

Browse Quizzes »