![]() |
Class Method to Calculate Age Doesn't Work - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Class Method to Calculate Age Doesn't Work (/thread-35413.html) |
Class Method to Calculate Age Doesn't Work - gdbengo - Oct-30-2021 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: Thank you
RE: Class Method to Calculate Age Doesn't Work - Yoriz - Oct-30-2021 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()
|