06.py (1114B)
1 #!/usr/bin/env python3 2 class Animal(): 3 """Base class for animals""" 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 # class method, note how `self` is passed as argument 9 def speak(self): 10 """Sounds animals can make""" 11 raise NotImplementedError 12 13 14 class Dog(Animal): # Dog is a derived class, it inherits from Animal 15 """Dog is a derived Animal class""" 16 def speak(self): 17 """Special sounds dogs make""" 18 return "Woof" 19 20 def my_id(self): 21 print(id(self)) 22 23 24 class Cat(Animal): # Cat is a derived class, it inherits from Animal 25 """Cat is a derived Animal class""" 26 def __init__(self, name, age): 27 self.name = f"A very special cat: {name}" # cats have a special name string 28 29 def speak(self): 30 """Special sounds cats make""" 31 return "Meow" 32 33 34 dog = Dog("Snoopy", 6) 35 cat = Cat("Kitty", 4) 36 print(dog.speak()) 37 print(cat.speak()) 38 39 if isinstance(dog, Animal): 40 print(f"dog ({id(dog)}) is an instance of Animal") 41 if isinstance(cat, Animal): 42 print(f"cat ({id(cat)}) is an instance of Animal")