Lesson Objective
- Understand Polymorphism.
KS3, GCSE, A-Level Computing Resources
Polymorphism, which translates to "many forms," arises when we have multiple classes connected through inheritance.
Inheritance enables the acquisition of attributes and methods from another class.
Polymorphism, in turn, utilizes these inherited methods to carry out alternate but similar tasks. This flexibility permits the execution of a single action in different ways.
class Student: def __init__(self, name, age): self.name = name self.age = age def valid_age(self): if 11 <= self.age <= 16: print("Age Valid") else: print("Age Invalid") def get_name(self): return self.name def set_name(self, name): self.name = name def get_age(self): return self.age def set_age(self, age): self.age = age class P16_Student(Student): def __init__(self, name, age, ucas): super().__init__(name, age) self.ucas = ucas def valid_age(self): if 16 <= self.age <= 19: print("Age Valid") else: print("Age Invalid") def get_ucas(self): return self.ucas def set_ucas(self, ucas): self.ucas = ucas if __name__ == "__main__": stu24 = P16_Student("Fei", 17, False) print(stu24.get_name(), "is", stu24.get_age()) print("UCAS complete:", stu24.get_ucas()) stu24.valid_age() stu25 = P16_Student("Bram", 12, False) stu25.valid_age() stu1 = Student("Bram", 12) stu1.valid_age()
Fei is 17 UCAS complete: false Age Valid Age Invalid Age Valid