In designing objects in information sytems, determining relationships between objects is a skill which a designer or analyst must master. One common relationship type is the Generalization/Specification type. The type defines a hierarchy which consists of a superclass and multiple subclasses. A subclass inherits everything from its superclass, which is referred to as inheritance in the object-orientation methodology and object-oriented programming. By inheritance, the superclass’s attributes will not repeat in any of its subclasses. When a new object of subclass is created, no extra object of the superclass is needed.
The following Python code shows you how to implement two classes: Person and Student. Student inherits all the attributes, fname and lname, as well as the methods, initializer and toString, from Person. In addition, Student has its own attribute: year.
Run the Code
Copy of Source Code
#Define the Person class class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.__class__.__name__,":", self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() #Define a Child class of Person class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.year = year def printname(self): super().printname() print(self.year) #Create a new Student object x = Student("Mike", "Olsen", 2019) x.printname() #Create a new Student object x = Student("Joker", "Lee", 2018) x.printname() #Create a new Student object x = Student("Swan", "Alter", 2017) x.printname()
- teaser by Kristijan Arsov on Unsplash