Python Forum

Full Version: Class Method to Calculate Age Doesn't Work
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone,

I'm new to Python programming, I need your help to fixing a code I'm working. It's a class that has a method that calculate a person age (instance of the class). This is my code:
from datetime import date

class personAge:
    def __init__(self, name, birthdate):
        self.name = name
        self.birthdate = birthdate
    def Name(self):
        return self.name

    def calc_age(self):
        today = date.today()
        over_trashold = (today.month, today.day) < (self.birthdate.month, self.birthdate.day)
        if over_trashold:
            return today.year - self.birthdate.year - 1
        return today.year - self.birthdate.year    
def main():
    person1 = personAge()
    person1.name = "Georges"
    person1.birthdate = date(1994, 12, 25)
    print(person1.name, person1.birthdate)


if __name__ == "__main__":
    main()
This is the error message I'm getting:
Error:
Traceback (most recent call last): File "class_age.py", line 24, in <module> main() File "class_age.py", line 17, in main person1 = personAge() TypeError: __init__() missing 2 required positional arguments: 'name' and 'birthdate'
Thank you
Your __init__ requires the arguments name and birthdate being passed to it.
The convention is for Class's to be CapWords and methods to be lower case.
The method Name is not required.
class PersonAge:
    def __init__(self, name, birthdate):
        self.name = name
        self.birthdate = birthdate

    def calc_age(self):
        today = date.today()
        over_trashold = (today.month, today.day) < (
            self.birthdate.month,
            self.birthdate.day,
        )
        if over_trashold:
            return today.year - self.birthdate.year - 1
        return today.year - self.birthdate.year


def main():
    name = "Georges"
    birthdate = date(1994, 12, 25)
    person1 = PersonAge(name, birthdate)
    print(person1.name, person1.birthdate)
    print(person1.calc_age())


if __name__ == "__main__":
    main()
Output:
Georges 1994-12-25 26