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.
Bu egzersiz
Introduction to Object-Oriented Programming in Python
kursunun bir parçasıdırEgzersiz talimatları
- 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, andbirth_year. - Within the method, create the
agevariable by calculating the difference between theCURRENT_YEARclass attribute andbirth_year. - Return the
nameandageattributes of the class.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
class Person:
CURRENT_YEAR = 2024
def __init__(self, name, age):
self.name = name
self.age = age
# Add a class method decorator
____
# Define the from_birth_year method
def ____(____, ____, ____):
# Create age
age = ____.____ - ____
# Return the name and age
return ____(____, ____)
bob = Person.from_birth_year("Bob", 1990)