Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading