In python I have getters and setters, and calculate utilities. The getters return the property, the setters set the property and the calculate utilities are functions that calculate stuff with the arguments. E.g.
obj.property = calculate_property(arguments)
However, there are various ways to implement calculate_property
, it could
calculate_property(self)
and return _property
My problem with 1) is that the arguments to calculate_property can be obscured because they might be contained within the object itself, and it is not possible to use the function outside of the object. In both 2 and 3 the functional form of calculate
is retained but the namespaces are different.
So I'm ruling out 1) for this reason.
IIf I go with 2) the advantage is that I can split all my utilities up into small files e.g. utilities_a.py, utilities_b.py and import them as modules.
If I go with 3) the functions remain in the same file making it overall longer, but the functions are encapsulated better.
Which is preferred between 2) and 3)? Or am I missing a different solution?
You can achieve both 2
and 3
with this example of adding a static method to your class that is defined in a separate file.
helper.py
:
def square(self):
self.x *= self.x
fitter.py
:
class Fitter(object):
def __init__(self, x: int):
self.x = x
from helper import square
if name == '__main__':
f = Fitter(9)
f.square()
print(f.x)
Output:
81
Adapted from this answer which was doing this for a class method. Seems to work for static method, too.