I am hoping to do some calculation using class methods and create a new attribute for each function (create_d and create_e). It doesn't feel very elegant because one has to run create_d before create_e. Is there a better way to organize them?
new_obj = TestClass(a, b, c)
new_obj.create_d(data)
new_obj.create_e(data)
class TestClass(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
def create_d(self, data):
self._d = math(data, self._a, self._b)
def create_e(self, data):
self._e = more_math(data, self._d)
As a comment says, you can pass data
as parameter
class TestClass(object):
def __init__(self, a, b, c, data):
self._a = a
self._b = b
self._c = c
self._d = math(data, self._a, self._b)
self._e = more_math(data, self._d)
Then to initialize:
new_obj = TestClass(a, b, c)
EDIT:
If you don't wanna carry self._d
and self._e
because their calculation is so expensive you can use properties
as below:
@property
def create_d(self, data):
return math(data, self._a, self._b)
@property
def create_(self, data):
return more_math(data, self._d)
And then when you need the values just call the properties
:
new_obj.create_d # return the calculation
Or if you're gonna use after just store it in a variable:
e = new_obj.create_e
You can check this out for more examples. Hope this can help you :)