Lesson Objective
- Understand Inheritance.
KS3, GCSE, A-Level Computing Resources
In Python, it is possible to inherit attributes and methods from one class to another. The "inheritance concept" is categorized into two groups:
In Python, to inherit from a class, you enter the name of the superclass into the brakets () as a parameter/.
In the following example, the P16_Student class (subclass) inherits the attributes and methods from the Student class (superclass)
class Student: # Private member variables (use getters/setters for access) __name = None __age = None 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): # Inherits from Student class pass def main(): stu24 = P16_Student() stu24.set_name("Fei") stu24.set_age(17) print(stu24.get_name(), "" , str(stu24.get_age())) main()
Fei is 17
super is used to refer to the superclass, which will send data to the constructor in the superclass to the subclass.
class Student: def __init__(self, name, age): self.name = name self.age = age 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 // New P16_Student Constructor has been created in this class. super is used to specify which parameters are inherited from the student superclass. class P16_Student(Student): def __init__(self, name, age, ucas): super().__init__(name, age) self.ucas = ucas def get_ucas(self): return self.ucas def set_ucas(self, ucas): self.ucas = ucas def main(): stu24 = P16_Student("Fei", 17, False) print(stu24.get_name(), "is", stu24.get_age()) print("UCAS complete: ", stu24.get_ucas()) main()
Fei is 17 UCAS complete: false