Sobes.tech
Junior — Middle

Can you explain the concept of a property in programming and how it is used in classes?

sobes.tech AI

Answer from AI

A property in programming is a mechanism that allows managing access to a class attribute through methods, while using the syntax of accessing it as a regular field.

In Python, a property is created using the @property decorator for the getter and additional decorators for the setter and deleter.

This is convenient when:

  • Controlling reading and writing of a value (e.g., validating or transforming data).
  • Keeping the class interface unchanged when changing the internal implementation.

Example:

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value:
            raise ValueError("Name cannot be empty")
        self._name = value

p = Person("Ivan")
print(p.name)  # Ivan
p.name = "Peter"  # calls the setter

Thus, properties allow encapsulating access logic while maintaining a convenient syntax.