Inner
Classes
·
In
Python, we can define a class inside another class, which is called an
inner class.
·
An
inner class can access the variables and methods of the outer class.
Example:
class OuterClass:
def __init__(self):
self.x = 5
class InnerClass:
def __init__(self):
self.y = 10
outer_obj =
OuterClass()
inner_obj =
outer_obj.InnerClass()
print(inner_obj.y) # Output: 10
In
the above example, we have defined an inner class called InnerClass
inside the outer class OuterClass. We create an instance of the outer
class and then create an instance of the inner class using the outer class
instance.
Nested Class
·
A
nested class is a class that is defined inside another class, just like
an inner class.
·
The
difference is that a nested class is not dependent on the outer class,
whereas an inner class is.
Example:
class OuterClass:
def __init__(self):
self.x = 5
class NestedClass:
def __init__(self):
self.z = 15
nested_obj =
OuterClass.NestedClass()
print(nested_obj.z) # Output: 15
In the above example, we have defined a nested
class called NestedClass inside the outer class OuterClass. We
create an instance of the nested class using the syntax OuterClass.NestedClass().
We don't need to create an instance of the outer class before creating an
instance of the nested class.
Inner Class Vs Nested Class
Inner
Classes
- An inner class is defined inside another class and can access the variables and methods of the outer class.
- An instance of an inner class must be created using an instance of the outer class.
- An inner class is used to logically group classes and can improve code organization and readability.
- An inner class is dependent on the outer class and cannot exist without it.
Nested
Classes
- A nested class is defined inside another class but is not dependent on the outer class.
- An
instance of a nested class can be created without creating an instance of the outer
class.
- A nested class is used to logically group classes and can improve code organization and readability.
- A nested class is not dependent on the outer class and can exist without it.
In summary, the main difference between inner
classes and nested classes is their dependence on the outer class. Inner
classes are dependent on the outer class and cannot exist without it, while
nested classes are not dependent on the outer class and can exist
independently.
Inner Class Example
def
__init__(self, name):
self.name = name
self.head = self.Head()
class Head:
def __init__(self):
self.eyes = 2
self.ears = 2
self.nose = 1
print(f"Hello, my name is {self.name}. I have {self.head.eyes}
eyes, {self.head.ears} ears, and {self.head.nose} nose.")
john.introduce() # Output: Hello, my name is
John. I have 2 eyes, 2 ears, and 1 nose.
In the above example, we have defined a Human
class with an inner class Head. The Head class represents the head of a human
and contains attributes for the eyes, ears, and nose.
def
__init__(self, name, age, street, city, state):
self.name = name
self.age = age
self.address = self.Address(street, city,
state)
def
__str__(self):
return f"Name: {self.name}\nAge:
{self.age}\nAddress: {self.address}"
class Address:
def __init__(self, street, city, state):
self.street = street
self.city = city
self.state = state
def __str__(self):
return
f"{self.street},{self.city},{self.state}"
# Create Objects
person = Person("Gopal", 30,
"49 MC Road", "Vijayawada", "AP")
Example2:
Create a class Bus with a nested class Engine.
Engine should have a constructor that accepts horsepower and engine type as
arguments. Bus should have a constructor that accepts make, model, and an
instance of Engine. Create an instance of Bus and print its make, model,
horsepower, and engine type.
def
__init__(self, make, model, engine):
self.make = make
self.model
= model
self.engine = engine
def
print_details(self):
print(f"Make: {self.make}")
print(f"Model: {self.model}")
print(f"Engine Horsepower: {self.engine.horsepower}")
print(f"Engine Type: {self.engine.engine_type}")
class Engine:
def __init__(self, horsepower, engine_type):
self.horsepower = horsepower
self.engine_type = engine_type
my_engine = Bus.Engine(200, "diesel")
my_bus = Bus("Volvo",
"9700", my_engine)
my_bus.print_details()
The above code also can be used as follows:
class Bus:
def
__init__(self, make, model, engine):
self.make = make
self.model = model
self.engine = engine
def __str__(self):
return f"Make: {self.make}, Model: {self.model}, Engine Horsepower:
{self.engine.horsepower}, Engine Type:
{self.engine.engine_type}"
class Engine:
def __init__(self, horsepower, engine_type):
self.horsepower = horsepower
self.engine_type = engine_type
my_bus = Bus("Volvo",
"9700", my_engine)
print(my_bus)
Example 3:
Construct a class Bank with a nested class
Account. Account should have a constructor that accepts account number and
balance as arguments. Bank should have a constructor that accepts name and an
instance of Account. Add a method deposit to Account that increases the balance
by a specified amount. Add a method withdraw to Account that decreases the
balance by a specified amount if sufficient funds are available. Create an
instance of Bank and demonstrate how to deposit and withdraw funds from the
account.
class Bank:
def
__init__(self, name, account):
self.name = name
self.account = account
class Account:
def __init__(self, account_number, balance):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
else:
self.balance -= amount
print("Withdrawal successful")
my_account = Bank.Account("12345", 1000)
my_bank = Bank("My Bank",
my_account)
print(f"Initial balance: {my_bank.account.balance}")
my_bank.account.deposit(500)
print(f"Balance after deposit: {my_bank.account.balance}")
my_bank.account.withdraw(200)
print(f"Balance after withdrawal:
{my_bank.account.balance}")
my_bank.account.withdraw(2000)
Output:
Initial balance: 1000
Balance after deposit: 1500
Withdrawal successful
Balance after withdrawal: 1300
Insufficient funds
Exercises:
- A restaurant wants to keep track of its menu items. Design a MenuItem class with a nested Ingredient class. The MenuItem class should have attributes for name, description, price, and a list of Ingredient objects. The Ingredient class should have attributes for name and quantity. Implement methods to add and remove ingredients, set and get attributes, and a method to display the details of a menu item with its list of ingredients.
- A company wants to manage its employees' information. Design an Employee class with a nested Payroll class. The Employee class should have attributes for name, age, and an instance of Payroll. The Payroll class should have attributes for salary and pay frequency. Implement methods to set and get the attributes, and a method to display the details of an employee with their payroll information.
- You are working on a system for a hotel that manages room reservations. Create a Room class with an inner class called Reservation. Each Reservation object should have a start date, end date, and a guest name. The Room class should have a method called is_available that takes a start and end date as arguments and returns True if the room is available during that period.
- You are developing a program that manages a library of books. Create a Book class with an inner class called Loan. Each Loan object should have a due date and a borrower name. The Book class should have a method called is_available that returns True if the book is not currently on loan.
- You are creating a program for a restaurant that allows customers to place orders online. Create a Menu class with an inner class called MenuItem. Each MenuItem object should have a name, description, and price. The Menu class should have a method called get_item that takes a name as an argument and returns the corresponding MenuItem object. The MenuItem class should have a method called order that adds the item to a customer's order and returns the total cost of the order so far.
- You are building a music player application that can play songs from a user's library. Create a MusicPlayer class with an inner class called Song. Each Song object should have a title, artist, and duration. The MusicPlayer class should have a method called add_song that takes a Song object and adds it to the user's library. It should also have a method called play_song that takes a title as an argument and plays the corresponding Song.
- You are developing a system for managing a school's course offerings. Create a Course class with an inner class called Student. Each Student object should have a name and a grade. The Course class should have a method called add_student that takes a Student object and adds it to the course roster. It should also have a method called get_average_grade that returns the average grade of all students in the course.
- You are creating a program for a coffee shop that allows customers to place orders. Create a Menu class with an inner class called MenuItem. Each MenuItem object should have a name, description, and price. The Menu class should have a method called add_item that takes a MenuItem object and adds it to the menu. It should also have a method called place_order that takes a list of MenuItem objects and returns the total cost of the order.
Comments
Post a Comment