In this challenge, you must write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print “Age is not valid, setting age to 0”. In addition, you must write the following instance methods:
- yearPasses() should increase the
ageinstance variable by 1. - amIOld() should perform the following conditional actions:
- If
age< 13, print “You are young.” - If 13 <=
age< 18, print “You are a teenager.” - Otherwise, print “You are old.”
- If
Sample Input:
4 #t: number of ages that will be entered
-1
10
16
18
Sample Output:
Age is not valid, setting age to 0.
You are young.
You are young.
You are young.
You are a teenager.
You are a teenager.
You are old.
You are old.
You are old.
The most difficult part of this problem is understanding classes. HackerRank provides the user the following code, which I explain in detail below.
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
def yearPasses(self):
# Increment the age of the person in here
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
class
e.g. class Person:
You can think of a class as a blueprint from which you can make objects. Say you want to create people objects (as in the code above), where each person has the same characteristics: each has an age, and their age increases every year. Perhaps this is a program where users can create a character and input their age. The computer will return a statement about how old they are to the screen and keep track of their age as the years pass. A class can be anything that provides a blueprint. For example, a Dog class might take a dog’s name, birthdate, and breed. An Student class might take a student’s verbal, quant, and writing GRE scores. Within the class it could return individual scores, print their total verbal+quant score, or compare their score with the score of a different student.
__init__
e.g. def __init__(self,initialAge):
The __init__ method (prounced as the dunda init method) is the constructor for the class. This constructor contains the attributes of a class and is called whenever an instance object is created. If you are creating a new person with your Person class, the only attribute needed for this challenge is age. The age entered when a new person is created is stored in the initialAge variable. How about self? You will notice that every method within the class contains it. Self represents the instance of the class (in this case the particular person you are creating) and Python requires to be the first or only parameter of a method.
Inside the dunda init method, we assign the attributes to our instance object/new person which is represented as self within the class. I am assigning initialAge to age for the instance object since their age will change as the years pass.
def __init__(self,initialAge):
self.age = initialAge
For this problem, we actually want to return a message and set the age to be 0 if the user tries to give a person a negative age.
def __init__(self,initialAge):
if initialAge < 0:
self.age = 0
print("Age is not valid, setting age to 0.")
else:
self.age = initialAge
A constructor can be given more than one parameter. In the Student class, each student must have a verbal, quant and writing score.
def __init__(self, verbal, quant, writing):
self.verbal = verbal
self.quant = quant
self.writing = writing
Instance objects
e.g. p = Person(age)
To use the class to create an instance object, you can just use instanceobject = class(attributes).
p = Person(40) #p is our first person created and their initial age is set to 40
p2 = Person(3) #p2 is our second person created and their initial age is set to 3
p3 = Person(17) #p3 is our third person created and their initial age is set to 17
p, p2, and p3 are our people (instance objects). When the __init__ method is called, it sets the p.age = 40, p2.age = 3 and p3.age = 17.
Once instance objects are created, you can use them to call particular functions within the class like p.amIOld() to ask if person p is old or p2.yearPasses() to increase the age of person p2 by 1 year.
Accessor method
e.g. def amIOld(self):
Classes contain accessor methods in order to retrieve the values we put on objects. An accessor method does not mutate the attributes of an object, but simply returns them or creates another value created based off of them. For example, you might imagine a acessor method could exist within our Person class called getAge(). Calling p3.getAge() would simply return the age of person p3 to the user. The accessor method we are asked to finish is amIOld(self). This looks at the object (self), which has an age from the __init__ method, and determines if it’s young, a teenager, or old, based on the value, but does not change the value itself.
def amIOld(self):
if self.age < 13:
print("You are young.")
elif self.age >= 13 and self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
Recall that p3 had an initialAge of 17. So calling p3.amIOld() would return “You are a teenager.”
Mutator method
e.g. def amIOld(self):
A class may have a mutator method which mutates the attributes of an object. In this coding challenge, yearPasses() is a mutator method because it changes the age of an instance object.
def yearPasses(self):
self.age += 1
Recall that p had an initialAge of 40. If you run p.yearPasses(), it would add 1 to their age and p’s age would now be 41.
Sample Solution:
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
self.age = 0
print("Age is not valid, setting age to 0.")
else:
self.age = initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if self.age < 13:
print("You are young.")
elif self.age >= 13 and self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
self.age += 1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")