Python - Write program to extend a class

Requirements

Define a new class, MySubClass, that inherits all of MyClass's names and provides one new method for displaying the data.

Here is the MyClass


class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods 
        self.data = value       # self is the instance 
    def display(self): 
        print(self.data)        # self.data: per instance 

Demo

class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods 
        self.data = value       # self is the instance 
    def display(self): 
        print(self.data)        # self.data: per instance 
# w w w.jav a  2  s .c  om
class MySubClass(MyClass):                   # Inherits setdata 
    def display(self):                           # Changes display 
        print('Current value = "%s"' % self.data) 

z = MySubClass() 
z.setdata(42)           # Finds setdata in MyClass 
z.display()             # Finds overridden method in MySubClass 
x = MyClass()                # Make two instances 
x.display()             # x is still a MyClass instance (old message)

Result

MySubClass defines the display method to print with a different format.

By defining an attribute with the same name as an attribute in MyClass, MySubClass replaces the display attribute in its superclass.

MySubClass specializes MyClass by changing the behavior of the display method.

MySubClass still inherits the setdata method in MyClass.

Related Topic