Unit V Classes and objects,Object oriented programming terminology & Function Overloading | Cse 108 Python Programming |B.tech cse

 


 Classes and objects,Object oriented programming terminology & Function Overloading 

1. What is a Class?

A class is like a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that the objects created from the class will have.

Think of a class as a recipe for creating objects, and objects are the instances of that class.

Creating a Class:

In Python, you define a class using the class keyword, followed by the class name. Conventionally, class names are written in CamelCase (each word starts with a capital letter).

class Dog: # Constructor (initializer) method to set up initial values def __init__(self, name, age): self.name = name # Instance attribute for the dog's name self.age = age # Instance attribute for the dog's age # A method to display the dog's information def display_info(self): print(f"Dog's Name: {self.name}, Age: {self.age} years old")

2. Creating Instance Objects

An object is an instance of a class. When you create an object, you're making a specific instance of the class with particular values for the attributes.

Creating an Object:

# Creating an object of the Dog class my_dog = Dog("Buddy", 5) # Accessing the object's attributes print(my_dog.name) # Output: Buddy print(my_dog.age) # Output: 5 # Calling the method of the object my_dog.display_info() # Output: Dog's Name: Buddy, Age: 5 years old

Here, my_dog is an object (an instance) of the Dog class. When we create my_dog, Python runs the __init__() method to initialize the name and age attributes.

3. Accessing Attributes and Methods

To access the attributes or methods of an object, we use the dot (.) notation:

  • Accessing Attributes: my_dog.name, my_dog.age
  • Calling Methods: my_dog.display_info()

Object-Oriented Programming Terminology

4. Inheritance:

Inheritance is a fundamental concept in OOP. It allows one class (child class) to inherit the attributes and methods of another class (parent class). This promotes code reuse and allows the child class to extend or modify the behavior of the parent class.

Think of inheritance as creating a new type that is a specialized version of an existing type.

Creating a Parent and Child Class (Inheritance Example):

# Parent class class Animal: def __init__(self, species): self.species = species # Animal's species def speak(self): print("The animal makes a sound.") # Child class inherits from Animal class Dog(Animal): def __init__(self, name, age, breed): super().__init__("Dog") # Calling the parent class constructor self.name = name self.age = age self.breed = breed # Overriding the speak method in the child class def speak(self): print(f"{self.name} says Woof!")

In this example:

  • Dog inherits from the Animal class.
  • The Dog class inherits the species attribute and the speak() method from Animal.
  • We override the speak() method in the Dog class to give it specific behavior for dogs (making the dog bark, "Woof!").

Creating Objects from the Child Class:

# Create a Dog object my_dog = Dog("Buddy", 3, "Golden Retriever") # Accessing inherited attribute print(my_dog.species) # Output: Dog # Calling overridden method my_dog.speak() # Output: Buddy says Woof!
  • The Dog object inherits the species attribute from Animal and can call the speak() method, but it also has its own speak() method that overrides the parent class's version.

5. Method Overriding:

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. In our previous example, we saw method overriding in action when the Dog class provided its own version of the speak() method.

  • Why is it useful?
    • Overriding allows a subclass to provide a more specific behavior while still retaining the structure of the method in the parent class.

Example of Method Overriding:

class Animal: def sound(self): print("This animal makes a sound.") class Dog(Animal): def sound(self): # Overriding the sound method print("Woof! Woof!") # Create instances of both classes dog = Dog() dog.sound() # Output: Woof! Woof! animal = Animal() animal.sound() # Output: This animal makes a sound.

Here, Dog provides a more specific sound() method than Animal, overriding the method.


6. Data Hiding (Encapsulation):

Data Hiding (or Encapsulation) is an important concept where we restrict access to certain details of an object and allow access only through specific methods (getters and setters). This helps prevent direct access to an object's internal state, which improves security and code maintainability.

In Python, we can hide attributes by using underscores. A single underscore (_) indicates that an attribute is protected (intended for internal use by the class or its subclasses), and a double underscore (__) makes the attribute private (more hidden).

Example of Data Hiding (Encapsulation):

class Dog: def __init__(self, name, age): self._name = name # Protected attribute self.__age = age # Private attribute # Getter method for the private attribute __age def get_age(self): return self.__age # Setter method for the private attribute __age def set_age(self, age): if age > 0: self.__age = age else: print("Age must be positive.") # Creating an object of Dog my_dog = Dog("Buddy", 5) # Accessing protected attribute print(my_dog._name) # This is allowed but not recommended # Trying to access private attribute directly (will cause error) # print(my_dog.__age) # This will raise an error! # Using getter to access private attribute print(my_dog.get_age()) # Output: 5 # Using setter to change the dog's age my_dog.set_age(6) print(my_dog.get_age()) # Output: 6
  • __age is a private attribute, so we cannot access it directly.
  • We use getter (get_age()) and setter (set_age()) methods to interact with __age.
  • By using getter and setter methods, we can control how the attribute is accessed and modified, adding a layer of security to the class.

7. Function Overloading (Method Overloading):

Function overloading or method overloading refers to defining multiple methods with the same name but different parameter lists (number or type of parameters). However, Python does not support function overloading in the traditional sense like languages such as Java or C++.

In Python, we can achieve similar behavior by using default arguments or variable-length arguments (e.g., *args, **kwargs).

Example of Function Overloading (Using Default Arguments):

class Calculator: def add(self, a, b=0): # Default value for b return a + b calc = Calculator() print(calc.add(5)) # Output: 5 (only one argument, b is defaulted to 0) print(calc.add(5, 3)) # Output: 8 (both arguments are provided)
  • If only one argument is passed to add(), the second argument (b) defaults to 0.
  • This mimics function overloading, where different behavior occurs based on the number of arguments passed.

Summary of Key Concepts:

  1. Classes and Objects:

    • Class: A blueprint for creating objects.
    • Object: An instance of a class.
    • We define methods (functions) inside classes to define behaviors.
  2. Inheritance:

    • A subclass inherits attributes and methods from a superclass.
    • It can also override methods for specialized behavior.
  3. Method Overriding:

    • Subclass provides its own implementation of a method already defined in the superclass.
  4. Data Hiding (Encapsulation):

    • Restricting access to an object's internal state.
    • Private and protected attributes are used to control access, usually with getters and setters.
  5. Function Overloading:

    • Python doesn't support traditional function overloading, but we can use default parameters or *args/**kwargs to handle different numbers of arguments.

Example: A Simple Dog Class

In this example, we will create a simple Dog class that allows us to:

  • Define a dog's name and age when we create a dog.
  • Access the dog's information.
  • Call a method to make the dog "speak" (i.e., print a message).
# Define the Dog class class Dog: # Constructor to initialize the dog's attributes def __init__(self, name, age): self.name = name # Dog's name self.age = age # Dog's age # Method to make the dog speak def speak(self): print(f"{self.name} says Woof!") # Method to display the dog's details def display_info(self): print(f"Name: {self.name}") print(f"Age: {self.age} years old") # Create a Dog object (an instance of the Dog class) my_dog = Dog("Buddy", 3) # Access the dog's information using the methods my_dog.display_info() # Show the dog's name and age my_dog.speak() # Make the dog speak # Create another Dog object another_dog = Dog("Max", 5) another_dog.display_info() # Show the second dog's details another_dog.speak() # Make the second dog speak

Explanation:

  1. Class Dog:

    • We define a class Dog with two attributes: name and age.
    • The __init__() method is the constructor, which is called when a new dog is created. It sets the name and age for each dog.
    • The speak() method is used to make the dog say "Woof!" when called.
    • The display_info() method shows the name and age of the dog.
  2. Creating an Object:

    • We create a Dog object called my_dog with the name "Buddy" and age 3 by calling Dog("Buddy", 3).
    • We then call my_dog.display_info() to print Buddy's name and age, and my_dog.speak() to make Buddy bark.
  3. Creating Another Object:

    • We create another dog named "Max" with the age 5 and use the same methods to display information and make him speak.

Output:

Name: Buddy Age: 3 years old Buddy says Woof! Name: Max Age: 5 years old Max says Woof!

Key Concepts Covered:

  1. Class: The Dog class is a blueprint for creating dog objects.
  2. Object: my_dog and another_dog are objects (instances) of the Dog class.
  3. Attributes: name and age are attributes that each Dog object has.
  4. Methods: speak() and display_info() are methods that perform actions using the object's data.

Post a Comment

If you have any doubt, Please let me know.

Previous Post Next Post