Python Property Class
In Python, the property class is a built-in class that allows you to define methods that behave like instance variables. This can be useful for implementing getters, setters, and deleters for instance variables, or for adding additional behaviour when accessing instance variables.
Here’s an example of how the property class may be used to build a basic getter and setter for an instance variable:
class MyClass:
def __init__(self, value):
self._value = value
def get_value(self):
return self._value
def set_value(self, value):
self._value = value
value = property(get_value, set_value)
obj = MyClass(5)
print(obj.value) # prints 5
obj.value = 6
print(obj.value) # prints 6
You can also use the @property decorator to define the getter and setter methods more concisely:
Class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
obj = MyClass(5)
print(obj.value) # prints 5
obj.value = 6
print(obj.value) # prints 6
In addition to the @property and @<property>. setter decorators, you can also use the @<property>.deleter decorator to define a method that is called when the del statement is used to delete the property. For example:
Class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
@value.deleter
def value(self):
del self._value
obj = MyClass(5)
print(obj.value) # prints 5
del obj.value
print(obj.value) # raises an AttributeError
The property class in Python allows you to define methods that behave like instance variables and can be useful for implementing getters, setters, and deleters, or for adding additional behaviour when accessing instance variables.
The following parameters are passed to property():
fget is a function that returns the value of an attribute, also known as the getter method.
fset is a function that sets the value of an attribute, also known as the setter method.
fdel is an attribute deletion function.
doc is a docstring, sometimes known as a remark.