When `Cat` has no `__init__` at all, how does Python still know how to build a cat — and which `__str__` wins when both classes define one?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Write a class named Cat whose header says a cat is an animal, and give it an empty body — pass is a complete body. Do not write an __init__, a getter, a setter or a __str__ anywhere inside it.
Then create a cat aged 5, give it the name "fluffy" using the method the parent already provides, and assign the cat object itself to cat.
class Animal(object):
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=0):
self.age = newage
def set_name(self, newname=""):
self.name = newname
def __str__(self):
return "animal:" + str(self.name) + ":" + str(self.age)Inheriting __init__ by naming a parent type
Write class Cat(Animal): with no __init__ of its own, and record that Cat(5) takes only an age and arrives with self.age, self.name = None, both getters and both setters.
Overriding the parent's __str__, and adding speak
Record that the child's __str__ wins over the parent's, trace c = Cat(5), c.set_name("fluffy"), print(c) and c.speak(), and note that a.speak() on an Animal object is an error.
The lookup chain ending at object
State the rule: check the type of the thing before the dot, then its parent, then the parent's parent up to the generic object, with an error only when nothing in the chain has the method.