9.1. Property About
Disable attribute modification
Logging value access
Check boundary
Raise exceptions such as
ValueErrororTypeErrorCheck argument type
In Python you can also define a setter method for a property using the
@propertyname.setter decorator. The setter method should have the same
name as the property, followed by .setter, and it should take a single
parameter that represents the new value of the property.
Here's an example of using the @propertyname.setter decorator to define a
read-write property of a class:
>>> class MyClass:
... x = property()
...
... @x.getter
... def x(self):
... return self.__dict__['x']
...
... @x.setter
... def x(self, value):
... self.__dict__['x'] = value
>>>
>>> # Create an instance of MyClass
>>> obj = MyClass()
>>>
>>> # Change the value of the property
>>> obj.x = 1
>>>
>>> # Access the property like an attribute
>>> print(obj.x)
1
In this example, the MyClass class defines a x = property().
The @x.getter decorator defines a getter method for the x property.
The x() method returns the value of the attribute from self.__dict__.
The @x.setter decorator defines a setter method for the x property.
The x() method takes a single parameter value that represents the new
value of the attribute.
The obj.x = 1 expression calls the x() setter method to set the value
of the attribute to 1. The obj.x expression calls the x()
getter method to retrieve the new value of the attribute.
9.1.1. SetUp
>>> from dataclasses import dataclass
>>> from datetime import date
9.1.2. Problem
>>> class Point:
... x: int
... y: int
... z: int
End-user's code:
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>> print(pt.x, pt.y, pt.z)
1 2 3
Let's introduce the same feature, that z-axis cannot be negative. And still we cannot change previously defined API (methods).
Woops, we don't have placeholders to inject such validation. We previously considered this as an overhead and we removed it. We are not future proof.
9.1.3. Solution
However in Python, you have properties, which is exactly for that reason.
>>> class Point:
... x: int
... y: int
... z = property()
...
... @z.getter
... def z(self):
... return self.__dict__['z']
...
... @z.setter
... def z(self, value):
... if value < 0:
... raise ValueError('Value cannot be negative')
... self.__dict__['z'] = value
End-users code is left unchanged:
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>> print(pt.x, pt.y, pt.z)
1 2 3
And new feature is working:
>>> pt.z = -1
Traceback (most recent call last):
ValueError: Value cannot be negative
9.1.4. Protocol
myattribute = property()- creates property@myattribute.getter- getter for attribute@myattribute.setter- setter for attribute@myattribute.deleter- deleter for attributeMethod name must be the same as attribute name
myattributehas to beproperty@property- creates property and a getter
>>> class MyClass:
... myattribute = property()
...
... @myattribute.getter
... def myattribute(self):
... return ...
...
... @myattribute.setter
... def myattribute(self):
... ...
...
... @myattribute.deleter
... def myattribute(self):
... ...
9.1.5. Property Descriptor
name = property()- creates propertyPreferred way
>>> class User:
... name = property()
...
... def __init__(self, name):
... self.name = name
...
... @name.getter
... def name(self):
... return self.__dict__['name']
...
... @name.setter
... def name(self, value):
... self.__dict__['name'] = value
...
... @name.deleter
... def name(self):
... self.__dict__['name'] = None
9.1.6. Property Decorator
@property- creates property and a getterTypically used when, there is only getter and no setter and deleter methods
>>> class User:
... def __init__(self, name):
... self.name = name
...
... @property
... def name(self):
... return self.__dict__['name']
...
... @name.setter
... def name(self, value):
... self.__dict__['name'] = value
...
... @name.deleter
... def name(self):
... self.__dict__['name'] = None
9.1.7. Property callable
name = property(fget=get_name, fset=set_name, fdel=del_name, doc='docstring for "name" property')Property's arguments are method references
get_name,set_name,del_nameand a docstringNot recommended
>>> class User:
... def __init__(self, name):
... self.name = name
...
... def get_name(self):
... return self.__dict__['name']
...
... def set_name(self, value):
... self.__dict__['name'] = value
...
... def del_name(self):
... self.__dict__['name'] = None
...
... name = property(
... doc='docstring for "name" property',
... fget=get_name,
... fset=set_name,
... fdel=del_name,
... )