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
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?