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)A subclass built through two levels of parents
Write class Student(Person) taking name, age and major=None, and record that the single line Person.__init__(self, name, age) builds the age, the name and the friends list, leaving self.major as the addition.
The randomized speak override
Record Student.speak drawing random.random() from the random library and branching on four quarters between 0 and 1, with __str__ overridden again to print student:name:age:major.
Class variables as a shared resource
Rank plain variables, instance variables and class variables, write tag = 1 directly in the class body outside any method, and state that one instance's change is visible to every other instance.
The Rabbit.tag counter trace
Write self.rid = Rabbit.tag followed by Rabbit.tag += 1 at the end of __init__, then trace Rabbit(8), Rabbit(6) and Rabbit(10) to rids 1, 2 and 3 with tag left at 4.