class LoggingDict(dict): def __setitem__(self, key, value): print('Setting %r to %r' % (key, value)) super().__setitem__(key, value) my_dict = LoggingDict({"city": "London"}) print (my_dict) my_dict["postcode"]= "SE10" print (my_dict) # Single and Multilevel Inheritance class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width # Here we declare that the Square class inherits from the Rectangle class class Square(Rectangle): def __init__(self, length): super().__init__(length, length) square = Square(4) print(square.area()) class Square(Rectangle): def __init__(self, length): super().__init__(length, length) class Cube(Square): def surface_area(self): face_area = super().area() return face_area * 6 def volume(self): face_area = super().area() return face_area * self.length cube = Cube(3) print (cube.surface_area()) print(cube.volume()) # Example for Multiple Inheritance # definition of the class starts here class Person: # defining constructor def __init__(self, person_name, person_age): self.name = person_name self.age = person_age # defining class methods def show_name(self): print(self.name) def show_age(self): print(self.age) # defining another class class Student: # Person is the def __init__(self, student_id): self.student_id = student_id def get_id(self): print(self.student_id) class Resident(Person, Student): # extends both Person and Student class def __init__(self, name, age, id): Person.__init__(self, name, age) Student.__init__(self, id) # Create an object of the subclass resident1 = Resident('John', 30, '102') resident1.show_name() resident1.get_id() # Polymorphism examples class Document: def __init__(self, name): self.name = name def show(self): raise NotImplementedError("Subclass must implement abstract method") class Pdf(Document): def show(self): return 'Show pdf contents!' class Word(Document): def show(self): return 'Show word contents!' documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3')] for document in documents: print(document.name + ': ' + document.show()) class Animal: # Constructor of the class def __init__(self, name): self.name = name # Abstract method, defined by convention only def talk(self): raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Grumpy Cat'), Dog('Lassie')] for animal in animals: print (animal.name + ': ' + animal.talk())