Page 413 - Computer_Science_F5
P. 413

Computer Science  # Accessing attributes using getter methods
                print(person.get_name())  # Output: John
                # Modifying attribute using setter method
                person.set_age(35)
          FOR ONLINE READING ONLY
                # Displaying information
                person.display_info()

             Output:









                               Figure 6.8: Output of encapsulation program code


           Inheritance in Python

           Inheritance is the process by which a new class (subclass or derived class) is created
           from an existing class (superclass or base class).

           Syntax:  In  Python, inheritance is declared by mentioning the superclass name
           in  parentheses after  the  subclass  name.  Subclasses  have  the  ability  to  override
           superclass methods, allowing them  to provide their  own implementations  or
           enhance the functionality of inherited methods. The following  Program Example
           6.5  demonstrate  inheritance in Python.


                     Program Example 6.5:
            Program codes demonstrating inheritance


                class Animal:
                    def speak(self):
                        print(“Animal speaks”)
                # Dog class inherits from Animal class

                class Dog(Animal):
                    def bark(self):
                        print(“Dog barks”)
                # Creating an object of the Dog class



                                                 404
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   404                                                     23/07/2024   12:34
   408   409   410   411   412   413   414   415   416   417   418