0% found this document useful (0 votes)
6 views

Inheritance

Inheritance in object-oriented programming allows one class to inherit properties and methods from another, promoting code reusability and organization. The document provides examples of simple single-level inheritance in Python, demonstrating how a child class can access methods from its parent class. It also describes various types of inheritance, including single, multilevel, hierarchical, multiple, and hybrid inheritance, along with the differences between public, private, and protected attributes.

Uploaded by

RajKumarThakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Inheritance

Inheritance in object-oriented programming allows one class to inherit properties and methods from another, promoting code reusability and organization. The document provides examples of simple single-level inheritance in Python, demonstrating how a child class can access methods from its parent class. It also describes various types of inheritance, including single, multilevel, hierarchical, multiple, and hybrid inheritance, along with the differences between public, private, and protected attributes.

Uploaded by

RajKumarThakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Inheritance:

What is inheritance. Write codes for a simple single level


inheritance. and explain each line
✅ What is Inheritance?

Inheritance is a feature in object-oriented programming (OOP) that allows one class (child or
derived class) to inherit properties and behaviors (methods) from another class (parent or base
class).

This helps in:

 Code reusability – You don't have to write the same code again.
 Organization – You can create a hierarchy of classes.

📌 Simple Single-Level Inheritance in Python


# Parent class
class Animal:
def speak(self):
print("Animal speaks")

# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")

# Creating object of child class


d = Dog()

# Accessing methods
d.speak() # Inherited from Animal
d.bark() # Defined in Dog

✅ Full Code:
python
CopyEdit
# Parent class
class Animal:
def speak(self):
print("Animal speaks")
# Child class
class Dog(Animal):
def bark(self):
print("Dog barks")

# Creating object of child class


d = Dog()

# Accessing methods
d.speak() # Inherited from Animal
d.bark() # Defined in Dog

🧠 Line-by-Line Explanation:
# Parent class

 This is a comment to indicate that the next block of code defines the parent (or base)
class.

class Animal:

 This defines a class named Animal.


 This is the base (or parent) class.
 All animals will share common behavior defined here.

def speak(self):

 This defines a method named speak() inside the Animal class.


 self refers to the current instance of the class (standard in Python class methods).

print("Animal speaks")

 When the speak() method is called, this line prints the message "Animal speaks".

# Child class

 A comment to indicate the next class is a child (derived) class.


class Dog(Animal):

 This defines a new class Dog that inherits from the Animal class.
 The Dog class will have access to all methods and attributes of the Animal class.

def bark(self):

 This defines a method named bark() specifically for the Dog class.
 It’s not part of Animal, so only Dog (and classes that inherit from it) will have it.

print("Dog barks")

 This prints "Dog barks" when the bark() method is called.

# Creating object of child class

 A comment stating that the next line creates an object of the Dog class.

d = Dog()

 Creates an object named d from the Dog class.


 Since Dog inherits from Animal, d can access methods from both Dog and Animal.

d.speak() # Inherited from Animal

 Calls the speak() method on the d object.


 This method is inherited from the Animal class.

d.bark() # Defined in Dog

 Calls the bark() method defined in the Dog class.


 This is specific to the Dog class and is not inherited from Animal.
🔚 Summary:

 Animal is the parent class.


 Dog is the child class that inherits from Animal.
 The Dog object can use both its own method (bark) and the inherited method (speak).

Would you like a diagram or real-world analogy to help further?

Give me codes for defining a contact base class with contacts as a list and its constructor to
initialize its name and email address. now create a class supplier derived from contact and its
own constructor calling the constructor of its base class .

Certainly! Here's a Python example demonstrating:

 A base class Contact with a class variable list of contacts and a constructor to initialize
name and email.
 A derived class Supplier that inherits from Contact and calls the base class constructor
using super().

✅ Full Code with Comments


# Base class
class Contact:
all_contacts = [] # Class variable to store all contact instances

def __init__(self, name, email):


self.name = name # Instance variable for name
self.email = email # Instance variable for email
Contact.all_contacts.append(self) # Add this contact to the list

# Derived class
class Supplier(Contact):
def __init__(self, name, email):
super().__init__(name, email) # Call the constructor of the base
class
# You can add more Supplier-specific initialization here if needed

🧪 Example Usage
# Create contact and supplier objects
c1 = Contact("Alice", "[email protected]")
s1 = Supplier("Bob's Supplies", "[email protected]")

# Print all contacts


for contact in Contact.all_contacts:
print(f"Name: {contact.name}, Email: {contact.email}")
🧠 What’s Happening?

Contact class:

 Has a class variable all_contacts to keep track of all contact instances.


 Its constructor (__init__) initializes name and email, and appends each new object to
all_contacts.

Supplier class:

 Inherits from Contact.


 Its constructor uses super().__init__(...) to call the parent constructor, ensuring
that name, email, and all_contacts setup is handled properly.

Let’s walk through each line of the code step by step so you understand exactly what’s
happening.

✅ Full Code:

# Base class
class Contact:
all_contacts = [] # Class variable to store all contact instances

def __init__(self, name, email):


self.name = name # Instance variable for name
self.email = email # Instance variable for email
Contact.all_contacts.append(self) # Add this contact to the list

# Derived class
class Supplier(Contact):
def __init__(self, name, email):
super().__init__(name, email) # Call the constructor of the base
class
# You can add more Supplier-specific initialization here if needed

🔍 Line-by-Line Explanation:

# Base class

 A comment indicating that the next class is the base (or parent) class.
class Contact:

 Defines a class named Contact.


 This class will hold contact information and be used as a parent class for others (like
Supplier).

all_contacts = []

 This is a class variable.


 It belongs to the Contact class (not to individual objects).
 It is used to keep track of all contact instances created.

def __init__(self, name, email):

 This is the constructor method, called automatically when you create a new Contact
object.
 self refers to the current object being created.
 name and email are input parameters.

self.name = name

 Stores the name parameter in the object.


 This makes name an instance variable accessible as object.name.

self.email = email

 Same as above, but for the email.


 Creates an instance variable email for the current object.

Contact.all_contacts.append(self)

 Adds the current object (self) to the shared class list all_contacts.
 This allows tracking of every contact created from the Contact class or any subclass
(like Supplier).
# Derived class

 A comment indicating the next class is a derived (child) class that will inherit from
Contact.

class Supplier(Contact):

 This creates a child class named Supplier.


 The Supplier class inherits from Contact, so it gets all the functionality of Contact.

def __init__(self, name, email):

 This defines the constructor for the Supplier class.


 It takes the same arguments as the base class: name and email.

super().__init__(name, email)

 super() is used to call the constructor of the parent class (Contact).


 This ensures that name, email, and all_contacts are set up properly for a Supplier
object.

# You can add more Supplier-specific initialization here if needed

 A comment suggesting you can add more code here to initialize other attributes specific
to Supplier.

🧪 Example Usage (Optional Test Code)


c1 = Contact("Alice", "[email protected]") # Creates a Contact
s1 = Supplier("Bob's Supplies", "[email protected]") # Creates a Supplier

for contact in Contact.all_contacts:


print(f"Name: {contact.name}, Email: {contact.email}")

This will output:


Name: Alice, Email: [email protected]
Name: Bob's Supplies, Email: [email protected]

Describe various types of inheritance


In Python (and most object-oriented languages), inheritance allows one class to use the
properties and methods of another. There are several types of inheritance, each serving different
design needs.

✅ 1. Single Inheritance
 One child class inherits from one parent class.
 Simplest form of inheritance.

📌 Example:
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Single Inheritance


def bark(self):
print("Dog barks")

✅ 2. Multilevel Inheritance
 A class is derived from a class that is already derived from another class (like a chain).

📌 Example:
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Dog inherits from Animal


def bark(self):
print("Dog barks")

class Puppy(Dog): # Puppy inherits from Dog (and indirectly from Animal)
def weep(self):
print("Puppy weeps")

✅ 3. Hierarchical Inheritance
 Multiple child classes inherit from the same parent class.

📌 Example:
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Dog inherits from Animal


def bark(self):
print("Dog barks")

class Cat(Animal): # Cat also inherits from Animal


def meow(self):
print("Cat meows")

✅ 4. Multiple Inheritance
 A class inherits from more than one parent class.
 Can be complex and lead to method resolution order (MRO) issues if not handled
carefully.

📌 Example:
class Father:
def skills(self):
print("Good at gardening")

class Mother:
def skills(self):
print("Good at cooking")

class Child(Father, Mother): # Multiple Inheritance


pass

c = Child()
c.skills() # Output: "Good at gardening" (because Father comes first)

✅ 5. Hybrid Inheritance
 A combination of two or more types of inheritance.
 May involve multiple and multilevel patterns.
 Can become complex and use Python's MRO to resolve conflicts.

📌 Example:
class A:
def method(self):
print("Method from A")

class B(A):
pass

class C(A):
pass

class D(B, C): # Hybrid (Multiple + Multilevel)


pass

🔍 Summary Table:
Type Description Example Classes
Single One child from one parent Dog(Animal)
Multilevel Child from a child (chain) Puppy(Dog(Animal))
Hierarchical Multiple children from one parent Dog(Animal), Cat(Animal)
Multiple One child from multiple parents Child(Father, Mother)
Hybrid Combination of above types D(B, C)

What are the differences between public , private and protected attributes?

🔓 1. Public
 Definition: Accessible from anywhere — inside or outside the class.
 How to Declare: Use a normal name without underscores.
 Example:

class User:
def __init__(self):
self.name = "John" # public

user = User()
print(user.name) # ✅ Works

🔐 2. Private

 Definition: Meant to be accessed only inside the class.


 How to Declare: Prefix the name with two underscores (__).
 Effect: Python uses name mangling (_ClassName__attribute) to make it harder to
access accidentally.
 Example:

class User:
def __init__(self):
self.__password = "secret" # private

def get_password(self):
return self.__password

user = User()
# print(user.__password) ❌ Error (AttributeError)
print(user.get_password()) # ✅ Works

# Still technically accessible like this (not recommended)


print(user._User__password) # 😬 Works (name mangling)

🟡 3. Protected (by convention only)

 Definition: Should be accessed only within the class and its subclasses.
 How to Declare: Prefix the name with a single underscore (_).
 Note: It's still accessible from outside, but developers treat it as a "do not touch" sign.
 Example:

class User:
def __init__(self):
self._email = "[email protected]" # protected

class Admin(User):
def show_email(self):
return self._email # ✅ Works in subclass
admin = Admin()
print(admin._email) # 😐 Works, but discouraged

🔁 Summary Table

Access Can be Accessed


Syntax Intended Use Enforced?
Type Outside?
Public name Anywhere ✅ Yes ❌ No
✅ Yes (but
Protected _name Within class and subclasses ❌ No
discouraged)
Only within the class 🔒 Partially (via name
Private __name ⚠️Not directly
(name mangled) mangling)

You might also like