Is there a 'correct' way to call a helper function when using an instance method in a class? Both functions calc_age and calc_age_v2 work, is there a preferred method? This is a toy example, the real code has more complex functions.
#%%
def calc_age(self):
age=2024-self.dob
return(age)
def calc_age_v2(self):
self.age=2024-self.dob
return(self)
class Person:
def __init__(self, name, dob,age):
self.name = name
self.dob = dob
self.age=age
def myfunc(self):
print("Hello my name is " + self.name)
def calc_age(self):
self.age=calc_age(self)
def calc_age_v2(self):
self=calc_age_v2(self)
p1 = Person(name="John",dob=2002,age=None)
# p1.calc_age()
p1.calc_age_v2()
print(p1.age)
There is no reason to return something from
calc_age_v2function when you modify the attribute in place (and I don't think it's a good idea to return the same class instance).I would use your first version of
calc_ageif you have to return only one result.