How do I use properties and setters in Python?

In Python, properties and setters are used to manage the attributes of a class. A property allows you to define methods in a class that can be accessed like attributes. This encapsulation provides a way to add validation and to control access to an attribute's value.

Here's how you can create properties and setters using the built-in `property()` function or the `@property` decorator. Below is an 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 isinstance(value, str): raise ValueError("Name must be a string.") self._name = value # Usage p = Person("Alice") print(p.name) # Output: Alice p.name = "Bob" # Sets the name to Bob print(p.name) # Output: Bob # p.name = 123 # This will raise ValueError

Python properties setters OOP encapsulation