Thursday, 29 May 2025

Unit 4: Object Oriented Programming with Python

 

Unit 4: Object Oriented Programming with Python     [10]

4.1 Class and Object

4.2 __init__ method

4.3 self keyword

4.4 Inheritance

4.5 Polymorphism and Data Hiding

Practical Works

       Write program to elaborate object oriented concept with simple examples.

       Write program to make use of __init__ method to initialize objects.

       Write program to apply different types of inheritance.

       Write program to elaborate polymorphism and data hiding concept.

 

4.1 Class and Object

Python Objects Classes

Python is an object-oriented programming language that offers classes, which are a potent tool for writing reusable code. To describe objects with shared characteristics and behaviours, classes are utilised. We shall examine Python's ideas of classes and objects in this article.

Classes in Python:

In Python, a class is a user-defined data type that contains both the data itself and the methods that may be used to manipulate it. In a sense, classes serve as a template to create objects. They provide the characteristics and operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can be seen as a class, and we can create as many objects of this class.

Creating Classes in Python

In Python, a class can be created by using the keyword class, followed by the class name. The syntax to create a class is given below.

Syntax

  1. class ClassName:    
  2.     #statement_suite     

In Python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite including fields, constructor, function, etc. definition.

Example:

Code:

class Person:  

    def __init__(self, name, age):  

        # This is the constructor method that is called when creating a new Person object  

        # It takes two parameters, name and age, and initializes them as attributes of the object  

        self.name = name  

        self.age = age  

    def greet(self):  

        # This is a method of the Person class that prints a greeting message  

        print("Hello, my name is " + self.name)  

Name and age are the two properties of the Person class. Additionally, it has a function called greet that prints a greeting.

Objects in Python:

An object is a particular instance of a class with unique characteristics and functions. After a class has been established, you may make objects based on it. By using the class constructor, you may create an object of a class in Python. The object's attributes are initialised in the constructor, which is a special procedure with the name __init__.

Syntax:

  1. # Declare an object of a class  
  2. object_name = Class_Name(arguments)   

Example:

Code:

class Person:  

    def __init__(self, name, age):  

        self.name = name    

        self.age = age      

    def greet(self):  

        print("Hello, my name is " + self.name)  

  

# Create a new instance of the Person class and assign it to the variable person1  

person1 = Person("Ayan", 25)  

person1.greet()    

Output:

"Hello, my name is Ayan"

 

4.2 __init__ method

In order to make an instance of a class in Python, a specific function called __init__ is called. Although it is used to set the object's attributes, it is often referred to as a constructor.

The self-argument is the only one required by the __init__ method. This argument refers to the newly generated instance of the class. To initialise the values of each attribute associated with the objects, you can declare extra arguments in the __init__ method.

Class and Instance Variables

All instances of a class exchange class variables. They function independently of any class methods and may be accessed through the use of the class name. Here's an illustration:

Code:

  1. class Person:  
  2.     count = 0   # This is a class variable  
  3.   
  4.     def __init__(self, name, age):  
  5.         self.name = name    # This is an instance variable  
  6.         self.age = age  
  7.         Person.count += 1   # Accessing the class variable using the name of the class  
  8. person1 = Person("Ayan", 25)  
  9. person2 = Person("Bobby", 30)  
  10. print(Person.count)     

Output:

2

Whereas, instance variables are specific to each instance of a class. They are specified using the self-argument in the __init__ method. Here's an illustration:

Code:

  1. class Person:  
  2.     def __init__(self, name, age):  
  3.         self.name = name    # This is an instance variable  
  4.         self.age = age  
  5. person1 = Person("Ayan", 25)  
  6. person2 = Person("Bobby", 30)  
  7. print(person1.name)    
  8. print(person2.age)     

Output:

Ayan

30

Class variables are created separately from any class methods and are shared by all class copies. Every instance of a class has its own instance variables, which are specified in the __init__ method utilising the self-argument.

 

4.3 self keyword

The self represents the class instance. We may access the class's properties and methods in Python using the "self" keyword. The keyword associates the properties with the class's arguments provided.

Since Python does not employ the @ syntax to create references to the instance attributes, we must use self. Python opted to implement methods so that the instance of the classes to which the method corresponds is automatically supplied but not immediately received: the first argument of any method is the instance on which the method is executed.

Exploring Object references with self

Example 1 : self keyword program

Code

  1. # Python program to show the use of the self keyword  
  2.     
  3. class Class:   
  4.     def __init__(self):   
  5.         print("The reference id of the self method is: ",id(self))   
  6.     
  7. # Creating an instance of the class  
  8. obj = Class()   
  9. print("The reference id of the object is: ",id(obj))  

Output

The reference id of the self method is:  139904481668400

The reference id of the object is:  139904481668400

 

4.4 Inheritance

In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in detail.

 

In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the derived class.

Python Inheritance

Syntax

 

    class derived-class(base class): 

        <class-suite>  

 

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.

 

Syntax

 

    class derive-class(<base class 1>, <base class 2>, ..... <base class n>): 

        <class - suite>  

 

Example 1

 

    class Animal: 

        def speak(self): 

            print("Animal Speaking") 

    #child class Dog inherits the base class Animal 

    class Dog(Animal): 

        def bark(self): 

            print("dog barking") 

    d = Dog() 

    d.bark() 

    d.speak() 

 

Output:

 

dog barking

Animal Speaking

Python Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.

Python Inheritance

The syntax of multi-level inheritance is given below.

Syntax

  1. class class1:  
  2.     <class-suite>   
  3. class class2(class1):  
  4.     <class suite>  
  5. class class3(class2):  
  6.     <class suite>  
  7. .  
  8. .  

Example

  1. class Animal:  
  2.     def speak(self):  
  3.         print("Animal Speaking")  
  4. #The child class Dog inherits the base class Animal  
  5. class Dog(Animal):  
  6.     def bark(self):  
  7.         print("dog barking")  
  8. #The child class Dogchild inherits another child class Dog  
  9. class DogChild(Dog):  
  10.     def eat(self):  
  11.         print("Eating bread...")  
  12. d = DogChild()  
  13. d.bark()  
  14. d.speak()  
  15. d.eat()  

Output:

dog barking

Animal Speaking

Eating bread...

Python Multiple inheritance

Python provides us the flexibility to inherit multiple base classes in the child class.

Python Inheritance

The syntax to perform multiple inheritance is given below.

Syntax

  1. class Base1:  
  2.     <class-suite>  
  3.   
  4. class Base2:  
  5.     <class-suite>  
  6. .  
  7. .  
  8. .  
  9. class BaseN:  
  10.     <class-suite>  
  11.   
  12. class Derived(Base1, Base2, ...... BaseN):  
  13.     <class-suite>  

Example

  1. class Calculation1:  
  2.     def Summation(self,a,b):  
  3.         return a+b;  
  4. class Calculation2:  
  5.     def Multiplication(self,a,b):  
  6.         return a*b;  
  7. class Derived(Calculation1,Calculation2):  
  8.     def Divide(self,a,b):  
  9.         return a/b;  
  10. d = Derived()  
  11. print(d.Summation(10,20))  
  12. print(d.Multiplication(10,20))  
  13. print(d.Divide(10,20))  

Output:

30

200

0.5

4.5 Polymorphism and Data Hiding

Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to the use of the same function name, but with different signatures, for multiple types.

Example of in-built polymorphic functions:

  1. # Python program for demonstrating the in-built poly-morphic functions  
  2.   
  3. # len() function is used for a string  
  4. print (len("Javatpoint"))  
  5.   
  6. # len() function is used for a list  
  7. print (len([110, 210, 130, 321]))  

Output:

10

4

 

Examples of user-defined polymorphic functions:

  1. # here, is a simple Python function  
  2. # for demonstrating the Polymorphism  
  3.   
  4. def add(p, q, r = 0):  
  5.     return p + q + r  
  6.   
  7. # Driver code  
  8. print (add(6, 23))  
  9. print (add(22, 31, 544))  

Output:

29

597

Polymorphism with Class Methods

Below is an example of how Python can use different types of classes in the same way. For loops that iterate through multiple objects are created. Next, call the methods without caring about what class each object belongs to. These methods are assumed to exist in every class.

Example:

  1. class xyz():  
  2.     def websites(self):  
  3.         print("Javatpoint is a website out of many availabe on net.")  
  4.   
  5.     def topic(self):  
  6.         print("Python is out of many topics about technology on Javatpoint.")  
  7.   
  8.     def type(self):  
  9.         print("Javatpoint is an developed website.")  
  10.   
  11. class PQR():  
  12.     def websites(self):  
  13.         print("Pinkvilla is a website out of many availabe on net. .")  
  14.   
  15.     def topic(self):  
  16.         print("Celebrities is out of many topics.")  
  17.   
  18.     def type(self):  
  19.         print("pinkvilla is a developing website.")  
  20.   
  21. obj_jtp = xyz()  
  22. obj_pvl = PQR()  
  23. for domain in (obj_jtp, obj_pvl):  
  24.     domain.websites()  
  25.     domain.topic()  
  26.     domain.type()  

Output:

Javatpoint is a website out of many availabe on net.

Python is out of many topics about technology on Javatpoint.

Javatpoint is an developed website.

Pinkvilla is a website out of many availabe on net.

Celebrities is out of many topics.

pinkvilla is a developing website.

Polymorphism with Inheritance:

Polymorphism allows us to define methods in Python that are the same as methods in the parent classes. In inheritance, the methods of the parent class are passed to the child class. It is possible to change a method that a child class has inherited from its parent class. This is especially useful when the method that was inherited from the parent doesn't fit the child's class. We re-implement such methods in the child classes. This is Method Overriding.

Example:

  1. class Birds:  
  2.     def intro1(self):  
  3.         print("There are multiple types of birds in the world.")  
  4.     def flight1(self):  
  5.         print("Many of these birds can fly but some cannot.")  
  6.   
  7. class sparrow1(Birds):  
  8.     def flight1(self):  
  9.         print("Sparrows are the bird which can fly.")  
  10.       
  11. class ostrich1(Birds):  
  12.     def flight1(self):  
  13.         print("Ostriches are the birds which cannot fly.")  
  14.       
  15. obj_birds = Birds()  
  16. obj_spr1 = sparrow1()  
  17. obj_ost1 = ostrich1()  
  18.   
  19. obj_birds.intro1()  
  20. obj_birds.flight1()  
  21.   
  22. obj_spr1.intro1()  
  23. obj_spr1.flight1()  
  24.   
  25. obj_ost1.intro1()  
  26. obj_ost1.flight1()  

Output:

There are multiple types of birds in the world.

Many of these birds can fly but some cannot.

There are multiple types of birds in the world.

Sparrows are the bird which can fly.

There are multiple types of birds in the world.

Ostriches are the birds which cannot fly.

 

Data hiding is a part of object-oriented programming, which is generally used to hide the data information from the user. It includes internal object details such as data members, internal working. It maintained the data integrity and restricted access to the class member. The main working of data hiding is that it combines the data and functions into a single unit to conceal data within a class. We cannot directly access the data from outside the class.

This process is also known as the data encapsulation. It is done by hiding the working information to user. In the process, we declare class members as private so that no other class can access these data members. It is accessible only within the class.

Data Hiding in Python

Python is the most popular programming language as it applies in every technical domain and has a straightforward syntax and vast libraries. In the official Python documentation, Data hiding isolates the client from a part of program implementation. Some of the essential members must be hidden from the user. Programs or modules only reflected how we could use them, but users cannot be familiar with how the application works. Thus it provides security and avoiding dependency as well.

We can perform data hiding in Python using the __ double underscore before prefix. This makes the class members private and inaccessible to the other classes.

Let's understand the following example.

Example -

  1. class CounterClass:  
  2.    __privateCount = 0  
  3.    def count(self):  
  4.       self.__privateCount += 1  
  5.       print(self.__privateCount)  
  6. counter = CounterClass()  
  7. counter.count()  
  8. counter.count()  
  9. print(counter.__privateCount)  

Output:

1

2

Traceback (most recent call last):

  File "<string>", line 17, in <module>

AttributeError: 'CounterClass' object has no attribute '__privateCount'

However we can access the private member using the class name.

  1. print(counter.CounterClass__privatecounter)  

Output:

1

2

2

 

 

No comments:

Post a Comment

Unit IV: Evaluation and Feedback | Teaching Method | Notes | Seven Semester | BICTE

📘 Unit IV: Evaluation and Feedback Total Time: 4 Hours 🔹 4.1 Assessing Student Performance with ICT ICT tools offer flexible, efficie...