-
Notifications
You must be signed in to change notification settings - Fork 156
Using Python Properties
In object-oriented programming, you can encounter with the concept of Mutator method where mutator means setter and accessor means getter. Although there is a strong opposition in using such methods for several contexts, for a well-defined mathematical system, getter and setter methods can prevent users making huge computational errors by enabling controlled access and integrated consistency checking.
Python comes with a function named property() which simplifies creating mutator and accessor methods. This function uses Python descriptor protocol to create these methods. @property
decorator is a syntactic sugar for the property()
function.
NURBS-Python makes use of Python properties to create getter and setter methods. For instance, degree
is a Curve class property and it should be used as follows:
from geomdl import NURBS
crv = NURBS.Curve() # create a NURBS curve instance
crv.degree = 3 # sets curve degree to 3
my_curve_degree = crv.degree # gets the curve degree and assigns it to a variable
print(my_curve_degree) # prints "3"
On the other hand, the following use would raise a TypeError
exception:
from geomdl import NURBS
crv = NURBS.Curve() # create a NURBS curve instance
crv.degree(3) # raises TypeError: 'int' object is not callable
my_curve_degree = crv.degree() # raises TypeError: 'int' object is not callable
A callable object is a function-like object. Python properties are not functions or methods, although they are defined like them.