pythonclassargumentsselfinstance-methods

Correct way to call helper function in a class


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)

Solution

  • There is no reason to return something from calc_age_v2 function when you modify the attribute in place (and I don't think it's a good idea to return the same class instance).

    # Use person instead of self for better understanding
    def calc_age(person):
        return 2024 - person.dob
    
    # Use person instead of self for better understanding
    def calc_age_v2(person):
        person.age = 2024 - person.dob
    
    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):
            calc_age_v2(self)
    

    I would use your first version of calc_age if you have to return only one result.