🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Lecture 3-Inheritance (python) - Read-Only.pptx

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Inheritance in Object- Oriented Programming (OOP) Understanding Inheritance with Examples in Python Overview of Object-Oriented Programming (OOP) OOP is a programming paradigm based on the concept of objects. Key concepts include: – 1. Encapsulation – 2. Abstract...

Inheritance in Object- Oriented Programming (OOP) Understanding Inheritance with Examples in Python Overview of Object-Oriented Programming (OOP) OOP is a programming paradigm based on the concept of objects. Key concepts include: – 1. Encapsulation – 2. Abstraction – 3. Inheritance – 4. Polymorphism Introduction to Inheritance Inheritance is a mechanism where one class acquires properties (fields) and behaviors (methods) of another class. The class that inherits is called a subclass (or derived class). The class being inherited from is called a superclass (or base class). Introduction to Inheritance Generalizatio n Why Use Inheritance? 1. Reusability of code. 2. Establishes a relationship between classes. 3. Makes it easier to understand and maintain the code. 4. Supports the 'is-a' relationship. Example of Inheritance (C#) Consider two classes: Animal and Dog. - Animal: Base class - Dog: Derived class class Animal class Dog : Animal { { private string Name public Dog(string name) : { get; set; } base(name) { } public Animal(string public void Bark() name) { { Console.WriteLine($"{Name} is Name = name; barking."); } } } } Example of Inheritance (Python) Consider two classes: Animal and Dog. - Animal: Base class - Dog: Derived class class Animal: class Dog(Animal): def __init__(self, def bark(self): name): self.name = print(f"{self.name} is name barking") # Example usage: dog = Dog("Buddy") dog.bark() Types of Inheritance 1. Single Inheritance 2. Multiple Inheritance – (Supported by Python, Not supported in C#) 3. Multilevel Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance – (Supported by Python, Not supported in C#) Single Inheritance (C#) In single inheritance, a class inherits from one superclass. class Animal class Dog : Animal { { private string Name public Dog(string name) : { get; set; } base(name) { } public Animal(string public void Bark() name) { { Console.WriteLine($"{Name} is Name = name; barking."); } } } } Vehicle Class: This is the base class with a Speed property and a Start method. Car Class: This is the derived class that inherits from Vehicle. It adds a Model property and a Drive method. Usage: In the Main method, an instance of the Car class is created. The Start method (inherited from Vehicle) and the Drive method (defined in Car) are both called, demonstrating simple inheritance in action. In this example, the Car class inherits the Speed property and Start method from the Vehicle class, allowing it to use these properties and methods as if they were part of the Car class. The Car class also introduces its own unique behaviour through the Single Inheritance(Python) In single inheritance, a class inherits from one superclass. class Animal: class Dog(Animal): def __init__(self, def bark(self): name): self.name = print(f"{self.name} is barking") name # Example usage: dog = Dog("Buddy") dog.bark() Code in C# Vehic // Base class class Vehicle { le private int Speed { get; set; } public void Start() { Console.WriteLine("Vehicle started."); Car } } UML Diagram // Derived class ??? class Car : Vehicle { private string Model { get; set; } public void Drive() { Console.WriteLine($"Driving at {Speed} km/h in a {Model} car."); } } // Usage class Program { static void Main(string[] args) { Car myCar = new Car(); myCar.Speed = 120; myCar.Model = "Toyota"; myCar.Start(); // Inherited method from Code in Python class Vehicle: def __init__(self, speed): self.speed = speed def start(self): print("Vehicle started") Vehicle class Car(Vehicle): def __init__(self, speed, model): super().__init__(speed) Car self.model = model def drive(self): print(f"Driving at {self.speed} km/h in a {self.model} car") # Example usage: mycar = Car(120, "Toyota") mycar.start() mycar.drive() 1.Vehicle class: 1. The Vehicle class has an __init__ method that initializes the speed field. 2. It also has a start method that, when called, prints "Vehicle started". 2.Car class: 1. The Car class inherits from the Vehicle class. 2. It has its own __init__ method that initializes both the speed field (inherited from Vehicle) and a new model field. 3. The drive method prints a message that includes the vehicle's speed and model. 3.Example usage: 1. An instance of the Car class is created with a speed of 120 km/h and a model "Toyota". 2. The start method is called to print "Vehicle started". 3. The drive method is called to print "Driving at 120 km/h in a Toyota car". Multiple Inheritance (Supported in Python, not supported in C#) Python supports multiple inheritances directly. C# does not support multiple inheritance directly. However, it can be achieved using interfaces. Father Mother Child Multiple Inheritance(Python) Animal mamm al Do g Multiple Inheritance(Python) # Base class 1 # Base class 2 class Animal: class Mammal: def __init__(self, def __init__(self, name): self.name = has_fur=True): name self.has_fur = has_fur def speak(self): def breathe(self): return "Some return "Breathing air" generic sound" class # Derived class Dog(Animal, Mammal): def __init__(self, name, breed): Animal.__init__(self, name) # Initialize Animal part Mammal.__init__(self) # Initialize Mammal part self.breed = breed def speak(self): return "Woof!" Multilevel Inheritance (C#) In multilevel inheritance, a class is derived from another derived class. class Animal class Puppy : Dog { { Animal public void Eat() public void Weep() { { Console.WriteLine("Eating" Console.WriteLine("Weeping") ); Dog } ; } } class Dog : Animal } { public void Bark() Puppy { Console.WriteLine("Barking "); } Multilevel Inheritance(python) In multilevel inheritance, a class is derived from another derived class (Python). class Animal: def eat(self): Animal print("Eating") # Example usage: puppy = Puppy() class Dog(Animal): puppy.eat() # Inherited from def bark(self): Animal puppy.bark() # Dog print("Barking") Inherited from Dog class Puppy(Dog): def weep(self): Puppy print("Weeping") Python 1.LivingBeing Class: 1. Contains the breathe method, representing a fundamental behavior of all living beings. 2.Animal Class: 1. Inherits from LivingBeing and adds the eat method, which is specific to animals. 3.Dog Class: 1. Inherits from Animal and introduces the bark method, which is specific to dogs. 4.Usage: 1. In the main section of the code, an instance of the Dog class is created. 2. The Dog object (my_dog) can call the breathe method from the LivingBeing class, the eat method from the Animal class, and the bark method from the Dog class. This structure shows how the Dog class can inherit properties and behaviors from both the Animal and LivingBeing classes, demonstrating multilevel inheritance in Python. C# // Base class // Derived class from Animal class LivingBeing class Dog : Animal { { public void Bark() public void Breathe() { { Console.WriteLine("Barking..."); } Console.WriteLine("Breathing..."); } } } // Usage class Program { // Intermediate class derived from static void Main(string[] args) LivingBeing { class Animal : LivingBeing Dog myDog = new Dog(); { public void Eat() myDog.Breathe(); // Inherited from { LivingBeing class myDog.Eat(); // Inherited from Animal Console.WriteLine("Eating..."); class } myDog.Bark(); // Method from Dog } class } } C# LivingBeing Class: This is the base class with a Breathe method, representing the fundamental behavior of all living beings. Animal Class: This is an intermediate class that inherits from LivingBeing. It adds an Eat method, which is specific to animals. Dog Class: This is the derived class that inherits from Animal. It introduces a Bark method, specific to dogs. Usage: In the Main method, an instance of the Dog class is created. The Dog object can: Call the Breathe method from the LivingBeing class. Call the Eat method from the Animal class. Call the Bark method from the Dog class. This demonstrates multilevel inheritance, where the Dog class inherits properties and methods from both the Animal and LivingBeing classes, forming a chain of inheritance. Python // Base class // Derived class from Animal class LivingBeing: class Dog(Animal): def breathe(self): def bark(self): print("Barking") print("Breathing") // Intermediate class derived from LivingBeing class Animal(LivingBeing): def eat(self): print("Eating") # Main if __name__ == "__main__": my_dog = Dog() my_dog.breathe() # Call the Breathe method from the LivingBeing class my_dog.eat() # Call the Eat method from the Animal class my_dog.bark() # Call the Bark method from the Dog class Python 1.LivingBeing Class: 1. Contains the breathe method, representing a fundamental behavior of all living beings. 2.Animal Class: 1. Inherits from LivingBeing and adds the eat method, which is specific to animals. 3.Dog Class: 1. Inherits from Animal and introduces the bark method, which is specific to dogs. 4.Usage: 1. In the main section of the code, an instance of the Dog class is created. 2. The Dog object (my_dog) can call the breathe method from the LivingBeing class, the eat method from the Animal class, and the bark method from the Dog class. This structure shows how the Dog class can inherit properties and behaviors from both the Animal and LivingBeing classes, demonstrating multilevel inheritance in Python. Hierarchical Inheritance In hierarchical inheritance, multiple classes inherit from the same superclass. (C#) class Dog : Animal Animal { public void Bark() { Dog Cat Console.WriteLine("Barking" ); } class Animal } class Cat : Animal { { public void Eat() public void Meow() { { Console.WriteLine("Eating" Console.WriteLine("Meowing"); ); } } } Hierarchical Inheritance In hierarchical inheritance, multiple classes inherit from the same superclass. (Python) Animal class Animal: def eat(self): print("Eating") Dog Cat class Dog(Animal): class Cat(Animal): def bark(self): def meow(self): print("Barking") print("Meowing") # Usage dog = Dog() dog.eat() # Inherited method from Animal class dog.bark() # Method from Dog class cat = Cat() cat.eat() # Inherited method from Animal class cat.meow() # Method C# // Derived class 2 class Motorcycle : Vehicle { public bool HasSidecar { get; set; } public void Ride() // Base class { class Vehicle string sidecarStatus = HasSidecar ? "with a sidecar" : "without a sidecar"; { Console.WriteLine($"Riding a {Brand} motorcycle public string Brand { get; set; } {sidecarStatus}."); } public void StartEngine() } { Console.WriteLine($"{Brand} engine // Usage class Program started."); { } static void Main(string[] args) } { Car myCar = new Car(); // Derived class 1 myCar.Brand = "Toyota"; class Car : Vehicle myCar.NumberOfDoors = 4; myCar.StartEngine(); // Inherited from Vehicle class { myCar.Drive(); // Specific to Car class public int NumberOfDoors { get; set; } Motorcycle myMotorcycle = new Motorcycle(); public void Drive() myMotorcycle.Brand = "Harley-Davidson"; { myMotorcycle.HasSidecar = true; Console.WriteLine($"Driving a myMotorcycle.StartEngine(); // Inherited from Vehicle class {Brand} car with {NumberOfDoors} myMotorcycle.Ride(); // Specific to Motorcycle doors."); class } } } } C#: Vehicle Class: This is the base class with a Brand property and a StartEngine method. Car Class: This class inherits from Vehicle and adds the NumberOfDoors property and Drive method. Motorcycle Class: This class also inherits from Vehicle and adds the HasSidecar property and Ride method. Usage: In the Main method: An instance of the Car class (myCar) is created. It uses both the StartEngine method from the Vehicle class and the Drive method specific to the Car class. An instance of the Motorcycle class (myMotorcycle) is created. It uses the StartEngine method from the Vehicle class and the Ride method specific to the Motorcycle class. This demonstrates hierarchical inheritance, where multiple derived classes (Car and Motorcycle) inherit from the same base class (Vehicle). Python # Base class Derived class 2 class Vehicle: class Motorcycle(Vehicle): def __init__(self, brand, has_sidecar): def __init__(self, brand): super().__init__(brand) self.brand = brand self.has_sidecar = has_sidecar def start_engine(self): print(f"{self.brand} engine def ride(self): started.") sidecar_status = "with a sidecar" if self.has_sidecar else "without a sidecar” print(f"Riding a {self.brand} motorcycle # Derived class 1 {sidecar_status}.") class Car(Vehicle): def __init__(self, brand, # Usage if __name__ == "__main__": number_of_doors): my_car = Car("Toyota", 4) super().__init__(brand) my_car.start_engine() # Inherited from Vehicle self.number_of_doors class my_car.drive() # Specific to Car class =number_of_doors my_motorcycle = Motorcycle("Harley-Davidson", True) my_motorcycle.start_engine() # Inherited def drive(self): from Vehicle class my_motorcycle.ride() # Specific print(f"Driving a {self.brand} car to Motorcycle class with {self.number_of_doors} doors.") Python: Vehicle Class: The base class Vehicle has a brand attribute and a method start_engine() that prints a message indicating the engine has started. Car Class: The Car class inherits from Vehicle. It has an additional attribute number_of_doors and a method drive() that prints a message about driving the car. Motorcycle Class: The Motorcycle class also inherits from Vehicle. It has an additional attribute has_sidecar and a method ride() that prints a message about riding the motorcycle, including whether it has a sidecar or not. Usage: Instances of Car and Motorcycle are created with their respective attributes. Methods from both the base class (start_engine()) and the derived classes (drive() and ride()) are called. Hybrid Inheritance Hybrid inheritance is a combination of two or more types of inheritance. In C#, this can be achieved through a combination of class inheritance and interface implementation. You can easily achieve hybrid inheritance in Python, which directly supports multiple inheritance. Python # Base class # Derived class (Multiple class Animal: inheritance) def eat(self): class Dolphin(Mammal, print("Eating") # Swimmer): def jump(self): Intermediate class 1 print("Jumping") class Mammal(Animal): def breathe(self): # Usage if __name__ == print("Breathing") # "__main__": Intermediate class 2 (Can be dolphin = Dolphin() thought of as an interface in dolphin.eat() # Inherited from C#) Animal class class Swimmer: dolphin.breathe() # Inherited def swim(self): from Mammal class print("Swimming") dolphin.swim() # Inherited from Swimmer Diamond Problem The Diamond Problem occurs in languages like C++ when a class inherits from two classes that have a common base class. C# avoids this problem by not supporting multiple inheritance directly. Class A Class B Class C Class D Example class A: def method(self): print("Method in A") class B(A): class C(A): def method(self): def method(self): print("Method in B") print("Method in C") class D(B, C): pass d = D() d.method()

Use Quizgecko on...
Browser
Browser