1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Object-Oriented Programming in Python

Connected

Exercise

Adding an alternative constructor

Class methods are a great way of allowing an alternative way to create an object from a class, such as by a file or by accepting different information and performing a task during the construction to return the required attributes.

In this exercise, you'll work with the Person class. The constructor expects a name and age during initialization. You will add a class method that allows initialization by providing name and birth year, where the method will then calculate age from the birth year.

Instructions

100 XP
  • Add a class method decorator.
  • Define the from_birth_year() class method, which accepts three arguments: the conventional word used as a special argument referring to the class, name, and birth_year.
  • Within the method, create the age variable by calculating the difference between the CURRENT_YEAR class attribute and birth_year.
  • Return the name and age attributes of the class.