How can the single line `Person.__init__(self, name, age)` set up the entire person part of a student, and what kind of variable hands every rabbit a unique ID?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Write Student, whose parent is Person. Creating one takes three things — a name, an age, and a major that is None when it is not supplied — so Student cannot reuse the two-parameter initializer it inherits and has to write its own. Build the whole person part of a student with a single call to the parent's initializer, made by class name, then add the one data attribute a student has that a person does not: major.
Then create a student named 'alice', aged 20, majoring in "CS", and assign it to student.
class Animal(object):
""" An animal with an age and a name """
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=""):
self.name = newname
def __str__(self):
return "animal:" + str(self.name) + ":" + str(self.age)
class Person(Animal):
""" An animal with a name from the start and a list of friends """
def __init__(self, name, age):
Animal.__init__(self, age)
self.set_name(name)
self.friends = []
def get_friends(self):
return self.friends
def add_friend(self, fname):
if fname not in self.friends:
self.friends.append(fname)
def speak(self):
print("hello")
def __str__(self):
return "person:" + str(self.name) + ":" + str(self.age)