Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
Inheritance allows classes to inherit properties from parent classes to promote code reuse. A child class inherits the parent's data members and functions and can also define its own implementation of parent functions. Python supports multi-level inheritance where a class can inherit from another derived class, as well as multiple inheritance from multiple parent classes. The issubclass() and isinstance() functions check class relationships and object types respectively. Method overriding allows child classes to provide specific implementations of parent class methods. Data abstraction in Python uses double underscores to hide attributes from external access.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance and polymorphism.
Some key points:
- Classes define the structure and behavior of an object using methods and attributes.
- Objects are instances of a class that contain data and allow methods to operate on that data.
- Inheritance allows a derived/child class to inherit attributes and methods from a base/parent class. The derived class can override or extend the parent class.
- Polymorphism allows derived classes to define their own implementation of a method while reusing the parent's implementation.
Inheritance allows classes to inherit attributes and methods from a parent class. Polymorphism allows a subclass to override a method from its parent class to perform the same action in different ways. For example, subclasses of Animal like Pig and Dog can override the animalSound() method to output different sounds. This allows a single animalSound() call to behave polymorphically based on the object's type. Inheritance creates an "is-a" relationship where a subclass is a type of its parent class.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance, polymorphism, and multiple inheritance. It provides examples of defining classes with methods and instantiating objects. Inheritance allows deriving a child class from a parent class to inherit attributes and methods. Methods can be overridden in the child class. Super() is used to explicitly call the parent class's method. Multiple inheritance allows a class to inherit from multiple parent classes.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
This document summarizes key concepts from a coding lesson including hashes, classes, variables scopes (global, instance, class), inheritance, and overriding methods. It discusses defining classes, creating objects, using methods, and accessing variables. Inheritance allows a class to inherit attributes and behaviors from a parent class. Derived classes can override methods from the parent class. The super keyword can call the parent method implementation.
The document discusses object-oriented programming concepts in C#, including defining classes, constructors, properties, static members, interfaces, inheritance, and polymorphism. It provides examples of defining a simple Cat class with fields, a constructor, properties, and methods. It also demonstrates using the Dog class by creating dog objects, setting their properties, and calling their bark method.
This document discusses object-oriented programming concepts like inheritance, polymorphism, overloading, and overriding. It provides examples of inheritance hierarchies for different types of birds. Inheritance allows subclasses to inherit attributes and methods from parent classes. Polymorphism means an object can have different implementations of the same method depending on its type. Overloading and overriding relate to creating multiple methods with the same name that differ in parameters or implementation.
1. Inheritance is a mechanism where a new class is derived from an existing class, known as the base or parent class. The derived class inherits properties and methods from the parent class.
2. There are 5 types of inheritance: single, multilevel, multiple, hierarchical, and hybrid. Multiple inheritance allows a class to inherit from more than one parent class.
3. Overriding allows a subclass to replace or extend a method defined in the parent class, while still calling the parent method using the super() function or parent class name. This allows the subclass to provide a specific implementation of a method.
This document discusses metaprogramming in Ruby, including object models, method dispatching, evaluation using class_eval, instance_eval, and eval, hooks for intercepting events, and building domain-specific languages. It provides examples of extending classes and objects at runtime through techniques like singleton classes, evaluation contexts, and method missing to add new behaviors dynamically. It also covers fluent interfaces and chaining methods to build internal domain-specific languages.
Python Programming - VIII. Inheritance and PolymorphismRanel Padon
The document discusses inheritance and polymorphism in Python programming. It provides background on object-oriented programming principles like inheritance, base and derived classes. It gives examples of inheritance with classes like Magulang (parent) and Anak (child), Rectangle and Square. It also explains polymorphism through examples of objects from different classes like Tatsulok and Bilog that can be treated the same due to a common superclass. Finally, it discusses abstract classes and gives an example with the abstract MgaTauhan class and derived classes.
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPTdeepuranjankumar08
The document discusses inheritance in Python. Inheritance allows a child class to inherit properties from a parent class. There are different types of inheritance including single, multi-level, multiple, and hierarchical inheritance. Single inheritance involves one parent and one child class, multi-level involves multiple generations of inheritance, multiple involves one child class with multiple parent classes, and hierarchical involves one parent class with multiple child classes. Examples of each type of inheritance in Python are provided.
The document discusses object-oriented programming concepts in PHP, including classes, objects, methods, properties, inheritance, and polymorphism. It provides examples of defining classes and using them to instantiate objects. Key concepts covered are class definitions, creating object instances, accessing object properties and methods, inheritance between classes, and overriding methods in child classes.
The document discusses object-oriented programming concepts in PHP, including classes, objects, methods, properties, inheritance, and polymorphism. It provides examples of defining classes and using them to instantiate objects. Key concepts covered are class definitions, creating object instances, accessing object properties and methods, and extending classes to create subclass hierarchies.
This document provides an overview of PHP classes and object-oriented programming. It defines what a class is conceptually and how to define a class in PHP, including defining attributes and methods. It explains how to instantiate class objects and use their methods. The document also covers class inheritance, constructors, and the differences between PHP4 and PHP5 object models.
This document discusses object-oriented programming (OOP) in PHP. It defines key OOP concepts like classes, objects, methods, and inheritance. It provides examples of creating classes and objects in PHP, and using concepts like constructors, multiple class instances, visibility, and building objects from scratch. The document aims to explain OOP and related terminology to help programmers transition to an object-oriented approach in PHP.
This document discusses inheritance in C++. It defines inheritance as a mechanism that allows classes to acquire properties from other classes. The class that inherits properties is called the derived or child class, while the class being inherited from is called the base or parent class. The key advantages of inheritance are that it saves memory, time, and development efforts by promoting code reuse. The document provides examples of single inheritance with one parent and one child class, and multiple inheritance with a class inheriting from multiple parent classes.
This document discusses inheritance in C++. It defines inheritance as a mechanism that allows classes to acquire properties from other classes. The class that inherits properties is called the derived or child class, while the class being inherited from is called the base or parent class. The key advantages of inheritance are that it increases code reusability, saves memory and development time. The document provides examples of single inheritance with one parent and one child class, and multiple inheritance with a class inheriting from more than one parent class.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses inheritance in object-oriented programming with C++. It defines inheritance as an "is-a" relationship where a subclass inherits properties from its base class. There are different types of inheritance like single, multilevel, multiple, and hybrid inheritance. The document provides examples of inheritance hierarchies and explains how inheritance is implemented in C++ using the colon symbol to specify a subclass and access specifiers to determine which members are inherited. It outlines advantages like code reusability and concludes with sample C++ code demonstrating a base class and derived class with inherited and new properties.
Inheritance allows classes to inherit attributes and methods from a parent class. Polymorphism allows a subclass to override a method from its parent class to perform the same action in different ways. For example, subclasses of Animal like Pig and Dog can override the animalSound() method to output different sounds. This allows a single animalSound() call to behave polymorphically based on the object's type. Inheritance creates an "is-a" relationship where a subclass is a type of its parent class.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance, polymorphism, and multiple inheritance. It provides examples of defining classes with methods and instantiating objects. Inheritance allows deriving a child class from a parent class to inherit attributes and methods. Methods can be overridden in the child class. Super() is used to explicitly call the parent class's method. Multiple inheritance allows a class to inherit from multiple parent classes.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
This document summarizes key concepts from a coding lesson including hashes, classes, variables scopes (global, instance, class), inheritance, and overriding methods. It discusses defining classes, creating objects, using methods, and accessing variables. Inheritance allows a class to inherit attributes and behaviors from a parent class. Derived classes can override methods from the parent class. The super keyword can call the parent method implementation.
The document discusses object-oriented programming concepts in C#, including defining classes, constructors, properties, static members, interfaces, inheritance, and polymorphism. It provides examples of defining a simple Cat class with fields, a constructor, properties, and methods. It also demonstrates using the Dog class by creating dog objects, setting their properties, and calling their bark method.
This document discusses object-oriented programming concepts like inheritance, polymorphism, overloading, and overriding. It provides examples of inheritance hierarchies for different types of birds. Inheritance allows subclasses to inherit attributes and methods from parent classes. Polymorphism means an object can have different implementations of the same method depending on its type. Overloading and overriding relate to creating multiple methods with the same name that differ in parameters or implementation.
1. Inheritance is a mechanism where a new class is derived from an existing class, known as the base or parent class. The derived class inherits properties and methods from the parent class.
2. There are 5 types of inheritance: single, multilevel, multiple, hierarchical, and hybrid. Multiple inheritance allows a class to inherit from more than one parent class.
3. Overriding allows a subclass to replace or extend a method defined in the parent class, while still calling the parent method using the super() function or parent class name. This allows the subclass to provide a specific implementation of a method.
This document discusses metaprogramming in Ruby, including object models, method dispatching, evaluation using class_eval, instance_eval, and eval, hooks for intercepting events, and building domain-specific languages. It provides examples of extending classes and objects at runtime through techniques like singleton classes, evaluation contexts, and method missing to add new behaviors dynamically. It also covers fluent interfaces and chaining methods to build internal domain-specific languages.
Python Programming - VIII. Inheritance and PolymorphismRanel Padon
The document discusses inheritance and polymorphism in Python programming. It provides background on object-oriented programming principles like inheritance, base and derived classes. It gives examples of inheritance with classes like Magulang (parent) and Anak (child), Rectangle and Square. It also explains polymorphism through examples of objects from different classes like Tatsulok and Bilog that can be treated the same due to a common superclass. Finally, it discusses abstract classes and gives an example with the abstract MgaTauhan class and derived classes.
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPTdeepuranjankumar08
The document discusses inheritance in Python. Inheritance allows a child class to inherit properties from a parent class. There are different types of inheritance including single, multi-level, multiple, and hierarchical inheritance. Single inheritance involves one parent and one child class, multi-level involves multiple generations of inheritance, multiple involves one child class with multiple parent classes, and hierarchical involves one parent class with multiple child classes. Examples of each type of inheritance in Python are provided.
The document discusses object-oriented programming concepts in PHP, including classes, objects, methods, properties, inheritance, and polymorphism. It provides examples of defining classes and using them to instantiate objects. Key concepts covered are class definitions, creating object instances, accessing object properties and methods, inheritance between classes, and overriding methods in child classes.
The document discusses object-oriented programming concepts in PHP, including classes, objects, methods, properties, inheritance, and polymorphism. It provides examples of defining classes and using them to instantiate objects. Key concepts covered are class definitions, creating object instances, accessing object properties and methods, and extending classes to create subclass hierarchies.
This document provides an overview of PHP classes and object-oriented programming. It defines what a class is conceptually and how to define a class in PHP, including defining attributes and methods. It explains how to instantiate class objects and use their methods. The document also covers class inheritance, constructors, and the differences between PHP4 and PHP5 object models.
This document discusses object-oriented programming (OOP) in PHP. It defines key OOP concepts like classes, objects, methods, and inheritance. It provides examples of creating classes and objects in PHP, and using concepts like constructors, multiple class instances, visibility, and building objects from scratch. The document aims to explain OOP and related terminology to help programmers transition to an object-oriented approach in PHP.
This document discusses inheritance in C++. It defines inheritance as a mechanism that allows classes to acquire properties from other classes. The class that inherits properties is called the derived or child class, while the class being inherited from is called the base or parent class. The key advantages of inheritance are that it saves memory, time, and development efforts by promoting code reuse. The document provides examples of single inheritance with one parent and one child class, and multiple inheritance with a class inheriting from multiple parent classes.
This document discusses inheritance in C++. It defines inheritance as a mechanism that allows classes to acquire properties from other classes. The class that inherits properties is called the derived or child class, while the class being inherited from is called the base or parent class. The key advantages of inheritance are that it increases code reusability, saves memory and development time. The document provides examples of single inheritance with one parent and one child class, and multiple inheritance with a class inheriting from more than one parent class.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses inheritance in object-oriented programming with C++. It defines inheritance as an "is-a" relationship where a subclass inherits properties from its base class. There are different types of inheritance like single, multilevel, multiple, and hybrid inheritance. The document provides examples of inheritance hierarchies and explains how inheritance is implemented in C++ using the colon symbol to specify a subclass and access specifiers to determine which members are inherited. It outlines advantages like code reusability and concludes with sample C++ code demonstrating a base class and derived class with inherited and new properties.
SVM introduction for machine learning engineersabigailjudith8
In essence, the AWS Machine Learning Foundations program serves as a starting point for those looking to build a solid understanding of machine learning principles and gain practical experience using AWS’s powerful machine learning services. It emphasizes scalable model development, deployment, and management within the cloud infrastructure provided by AWS.
מכונת קנטים המתאימה לנגריות קטנות או גדולות (כמכונת גיבוי).
מדביקה קנטים מגליל או פסים, עד עובי קנט – 3 מ"מ ועובי חומר עד 40 מ"מ. בקר ממוחשב המתריע על תקלות, ומנועים מאסיביים תעשייתיים כמו במכונות הגדולות.
Your startup on AWS - How to architect and maintain a Lean and Mean accountangelo60207
Prevent infrastructure costs from becoming a significant line item on your startup’s budget! Serial entrepreneur and software architect Angelo Mandato will share his experience with AWS Activate (startup credits from AWS) and knowledge on how to architect a lean and mean AWS account ideal for budget minded and bootstrapped startups. In this session you will learn how to manage a production ready AWS account capable of scaling as your startup grows for less than $100/month before credits. We will discuss AWS Budgets, Cost Explorer, architect priorities, and the importance of having flexible, optimized Infrastructure as Code. We will wrap everything up discussing opportunities where to save with AWS services such as S3, EC2, Load Balancers, Lambda Functions, RDS, and many others.
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Safe Software
Jacobs has developed a 3D utility solids modelling workflow to improve the integration of utility data into 3D Building Information Modeling (BIM) environments. This workflow, a collaborative effort between the New Zealand Geospatial Team and the Australian Data Capture Team, employs FME to convert 2D utility data into detailed 3D representations, supporting enhanced spatial analysis and clash detection.
To enable the automation of this process, Jacobs has also developed a survey data standard that standardizes the capture of existing utilities. This standard ensures consistency in data collection, forming the foundation for the subsequent automated validation and modelling steps. The workflow begins with the acquisition of utility survey data, including attributes such as location, depth, diameter, and material of utility assets like pipes and manholes. This data is validated through a custom-built tool that ensures completeness and logical consistency, including checks for proper connectivity between network components. Following validation, the data is processed using an automated modelling tool to generate 3D solids from 2D geometric representations. These solids are then integrated into BIM models to facilitate compatibility with 3D workflows and enable detailed spatial analyses.
The workflow contributes to improved spatial understanding by visualizing the relationships between utilities and other infrastructure elements. The automation of validation and modeling processes ensures consistent and accurate outputs, minimizing errors and increasing workflow efficiency.
This methodology highlights the application of FME in addressing challenges associated with geospatial data transformation and demonstrates its utility in enhancing data integration within BIM frameworks. By enabling accurate 3D representation of utility networks, the workflow supports improved design collaboration and decision-making in complex infrastructure projects
The State of Web3 Industry- Industry ReportLiveplex
Web3 is poised for mainstream integration by 2030, with decentralized applications potentially reaching billions of users through improved scalability, user-friendly wallets, and regulatory clarity. Many forecasts project trillions of dollars in tokenized assets by 2030 , integration of AI, IoT, and Web3 (e.g. autonomous agents and decentralized physical infrastructure), and the possible emergence of global interoperability standards. Key challenges going forward include ensuring security at scale, preserving decentralization principles under regulatory oversight, and demonstrating tangible consumer value to sustain adoption beyond speculative cycles.
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMAnchore
Over 70% of any given software application consumes open source software (most likely not even from the original source) and only 15% of organizations feel confident in their risk management practices.
With the newly announced Anchore SBOM feature, teams can start safely consuming OSS while mitigating security and compliance risks. Learn how to import SBOMs in industry-standard formats (SPDX, CycloneDX, Syft), validate their integrity, and proactively address vulnerabilities within your software ecosystem.
This OrionX's 14th semi-annual report on the state of the cryptocurrency mining market. The report focuses on Proof-of-Work cryptocurrencies since those use substantial supercomputer power to mint new coins and encode transactions on their blockchains. Only two make the cut this time, Bitcoin with $18 billion of annual economic value produced and Dogecoin with $1 billion. Bitcoin has now reached the Zettascale with typical hash rates of 0.9 Zettahashes per second. Bitcoin is powered by the world's largest decentralized supercomputer in a continuous winner take all lottery incentive network.
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureSafe Software
When projects depend on fast, reliable spatial data, every minute counts.
AI Clearing needed a faster way to handle complex spatial data from drone surveys, CAD designs and 3D project models across construction sites. With FME Form, they built no-code workflows to clean, convert, integrate, and validate dozens of data formats – cutting analysis time from 5 hours to just 30 minutes.
Join us, our partner Globema, and customer AI Clearing to see how they:
-Automate processing of 2D, 3D, drone, spatial, and non-spatial data
-Analyze construction progress 10x faster and with fewer errors
-Handle diverse formats like DWG, KML, SHP, and PDF with ease
-Scale their workflows for international projects in solar, roads, and pipelines
If you work with complex data, join us to learn how to optimize your own processes and transform your results with FME.
Domino IQ – What to Expect, First Steps and Use Casespanagenda
Webinar Recording: https://www.panagenda.com/webinars/domino-iq-what-to-expect-first-steps-and-use-cases/
HCL Domino iQ Server – From Ideas Portal to implemented Feature. Discover what it is, what it isn’t, and explore the opportunities and challenges it presents.
Key Takeaways
- What are Large Language Models (LLMs) and how do they relate to Domino iQ
- Essential prerequisites for deploying Domino iQ Server
- Step-by-step instructions on setting up your Domino iQ Server
- Share and discuss thoughts and ideas to maximize the potential of Domino iQ
If You Use Databricks, You Definitely Need FMESafe Software
DataBricks makes it easy to use Apache Spark. It provides a platform with the potential to analyze and process huge volumes of data. Sounds awesome. The sales brochure reads as if it is a can-do-all data integration platform. Does it replace our beloved FME platform or does it provide opportunities for FME to shine? Challenge accepted
Mastering AI Workflows with FME - Peak of Data & AI 2025Safe Software
Harness the full potential of AI with FME: From creating high-quality training data to optimizing models and utilizing results, FME supports every step of your AI workflow. Seamlessly integrate a wide range of models, including those for data enhancement, forecasting, image and object recognition, and large language models. Customize AI models to meet your exact needs with FME’s powerful tools for training, optimization, and seamless integration
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfRejig Digital
Unlock the future of oil & gas safety with advanced environmental detection technologies that transform hazard monitoring and risk management. This presentation explores cutting-edge innovations that enhance workplace safety, protect critical assets, and ensure regulatory compliance in high-risk environments.
🔍 What You’ll Learn:
✅ How advanced sensors detect environmental threats in real-time for proactive hazard prevention
🔧 Integration of IoT and AI to enable rapid response and minimize incident impact
📡 Enhancing workforce protection through continuous monitoring and data-driven safety protocols
💡 Case studies highlighting successful deployment of environmental detection systems in oil & gas operations
Ideal for safety managers, operations leaders, and technology innovators in the oil & gas industry, this presentation offers practical insights and strategies to revolutionize safety standards and boost operational resilience.
👉 Learn more: https://www.rejigdigital.com/blog/continuous-monitoring-prevent-blowouts-well-control-issues/
Enabling BIM / GIS integrations with Other Systems with FMESafe Software
Jacobs has successfully utilized FME to tackle the complexities of integrating diverse data sources in a confidential $1 billion campus improvement project. The project aimed to create a comprehensive digital twin by merging Building Information Modeling (BIM) data, Construction Operations Building Information Exchange (COBie) data, and various other data sources into a unified Geographic Information System (GIS) platform. The challenge lay in the disparate nature of these data sources, which were siloed and incompatible with each other, hindering efficient data management and decision-making processes.
To address this, Jacobs leveraged FME to automate the extraction, transformation, and loading (ETL) of data between ArcGIS Indoors and IBM Maximo. This process ensured accurate transfer of maintainable asset and work order data, creating a comprehensive 2D and 3D representation of the campus for Facility Management. FME's server capabilities enabled real-time updates and synchronization between ArcGIS Indoors and Maximo, facilitating automatic updates of asset information and work orders. Additionally, Survey123 forms allowed field personnel to capture and submit data directly from their mobile devices, triggering FME workflows via webhooks for real-time data updates. This seamless integration has significantly enhanced data management, improved decision-making processes, and ensured data consistency across the project lifecycle.
2. Introduction to OOP and Inheritance
Object-Oriented Programming (OOP):
- Focuses on objects that interact with each other.
- Concepts include classes, objects, inheritance, polymorphism,
encapsulation, and abstraction.
Inheritance:
- Inheritance is the mechanism that allows one class (child) to
inherit attributes and methods from another class (parent).
- Benefits of inheritance: Reusability, Extensibility, Improved code
organization.
3. Why Use Inheritance?
- Reusability: Child classes can reuse code from
the parent class, avoiding duplication.
- Extensibility: Child classes can extend the
functionality of parent classes.
- Simplifies Maintenance: Changes to the parent
class automatically reflect in the child classes.
4. Types of Inheritance
- Single Inheritance: A child class inherits from one parent class.
Example: class Dog(Animal):
- Multiple Inheritance: A child class inherits from more than one
parent class.
Example: class Dog(Mammal, Animal):
- Multilevel Inheritance: A class inherits from a class, which is itself
derived from another class.
Example: class Puppy(Dog):
5. Inheritance Syntax
Basic Syntax:
class ParentClass:
def __init__(self):
pass
def method_in_parent(self):
pass
class ChildClass(ParentClass): # Inherits from ParentClass
def __init__(self):
super().__init__() # Calls the constructor of ParentClass
pass
def method_in_child(self):
pass
6. Creating Objects for the Class
Class Object Instantiation:
When a class is defined, you can create objects (instances) of the class to
access its methods and attributes.
Example:
class Animal:
def __init__(self, name):
self.name = name
# Creating an object of Animal class
animal = Animal("Lion")
print(animal.name) # Output: Lion
7. Demonstrating Inheritance with Example
Parent Class:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
Child Class:
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} barks")
Creating Objects for the Child Class:
dog = Dog("Buddy", "Golden Retriever")
dog.speak() # Output: Buddy barks
8. # Parent class
class Parent:
def __init__(self):
self.parent_var = "I am a Parent variable"
def parent_method(self):
print("This is a method from Parent class")
# First Child class
class Child1(Parent):
def child1_method(self):
print("This is a method from Child1 class")
# Second Child class
class Child2(Parent):
def child2_method(self):
print("This is a method from Child2 class")
# Creating objects of child classes
obj1 = Child1()
obj2 = Child2()
# Accessing Parent class properties and methods
print(obj1.parent_var) # Accessing Parent's variable
obj1.parent_method() # Calling
9. class Animal:
def move(self):
print('Animals can move')
class Bird:
def fly(self):
print('Birds can fly')
class Bat(Animal, Bird):
def sound(self):
print('Bats make high-pitched sounds')
bat = Bat()
bat.move()
bat.fly()
bat.sound()
10. Python follows MRO when resolving
methods.
- The `__mro__` attribute shows the method
lookup order.
- Example:
print(Bat.__mro__)
Output:
(<class 'Bat'>, <class 'Animal'>, <class 'Bird'>,
<class 'object'>)
11. Method Overriding in Inheritance
Definition: The child class can provide its own implementation of a method that is already
defined in the parent class.
Example:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
animal = Animal()
animal.speak() # Output: Animal makes a sound
dog = Dog()
dog.speak() # Output: Dog barks
12. Super Function and Inheritance
The super() function is used to call methods from the parent class.
This is particularly useful in the child class constructor to call the parent class's __init__()
method.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the parent class constructor
self.breed = breed
def speak(self):
print(f"{self.name} barks")
dog = Dog("Buddy", "Golden Retriever")
dog.speak() # Output: Buddy barks
13. Private and Protected Attributes in
Inheritance
Private Attributes:
- Private attributes (using __) are not accessible outside the class, even in subclasses.
Example:
class Animal:
def __init__(self, name):
self.__name = name # Private attribute
def get_name(self):
return self.__name
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
dog = Dog("Buddy")
print(dog.get_name()) # Access private attribute via public method
14. Access Modifiers in Inheritance
• Public Attributes: Accessible from anywhere.
• Protected Attributes: Indicated by a single
underscore (_), meant for internal use within a
class or subclass.
• Private Attributes: Indicated by double
underscores (__), not directly accessible
outside the class or subclass.
15. Inheritance in Action - Example
Parent Class:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
Child Class:
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
class Cat(Animal):
def speak(self):
print(f"{self.name} meows")
dog = Dog("Buddy")
cat = Cat("Kitty")
dog.speak() # Buddy barks
cat.speak() # Kitty meows
16. Conclusion
- Inheritance allows one class to acquire
attributes and methods from another.
- It promotes code reuse and provides a way to
extend or modify functionality.
- You can override methods in the child class and
use super() to call the parent class's methods.