In-Depth Python OOP
In-Depth Python OOP
Properties are a mechanism in object-oriented programming that allow controlled access to protected and private attributes. They are defined using methods and can be accessed as if they were regular attributes. Properties provide a convenient and intuitive way to interact with an object's internal data.
Please take a look at the example below to get a general idea of how properties work, without diving too deep into the details:
Personclass demonstrates the usage of properties. The class has a constructor method
__init__that takes a parameter
nameand initializes the
_nameattribute with the provided value.
nameattribute is encapsulated within a property using the
@propertydecorator. This decorator indicates that the method directly below it (
namemethod in this case) should be treated as a getter method for the
nameproperty. The getter method, in this case, simply returns the value of the
To allow modification of the
nameattribute, a setter method is defined using the
@name.setterdecorator. This setter method, also named
name, takes a
valueparameter. When the property is assigned a new value (e.g.,
person.name = "Bob"), this setter method is called with the assigned value. In this case, the setter method sets the value of the
_nameattribute to the provided
The usage of the properties is demonstrated by creating an instance of the
personwith the name "John". The property
nameis accessed using
person.name, which invokes the getter method and returns the value of the
_nameattribute ("John"). The property is then modified by assigning a new value to it (
person.name = "Bob"), which calls the setter method and updates the
_nameattribute to "Bob". Finally, the modified property is accessed again using
person.name, resulting in the value "Bob" being printed.
In summary, properties in Python provide a way to encapsulate attribute access and modification within getter and setter methods. They allow you to define custom behavior when accessing or modifying an attribute, giving you more control over the attribute's behavior while providing a clean and consistent interface to interact with the class attributes.
Please note that this example is meant to provide a basic understanding of properties and their usage. More advanced concepts and nuances will be covered in subsequent chapters.
Everything was clear?