IKH

Inner Classes

  • Sometimes we can declare a class inside another class,such type of classes are called inner classes.
  • Without existing one type of object if there is no chance of existing another type of object,then we should go for inner classes.

Example

Python
Without existing Car object there is no chance of existing Engine object. Hence Engine 
class should be part of Car class.
class Car:
 .....
 class Engine:
 ......

Output

PowerShell
4

Example

Python
Without existing university object there is no chance of existing Department object
class University:
 .....
 class Department:
 ......

Output

PowerShell
8

Example

Python
Without existing Human there is no chance of existin Head. Hence Head should be part of Human.
class Human:
 class Head:

Note

  • Without existing outer class object there is no chance of existing inner class object. Hence inner class object is always associated with outer class object.

Example

Python
class Outer: 
def __init__(self): 
print("outer class object creation") 
class Inner: 
def __init__(self): 
print("inner class object creation") 
def m1(self): 
print("inner class method") 
o=Outer() 
i=o.Inner() 
i.m1() 

Output

PowerShell
outer class object creation
inner class object creation
inner class method

Note

  • The following are various possible syntaxes for calling inner class method.
  • o=Outer()
  • i=o.Inner()
  • i.m1()
  • i=Outer().Inner()
    i.m1()
  • Outer().Inner().m1()

Example

Python
class Person: 
def __init__(self): 
self.name='durga' 
self.db=self.Dob() 
def display(self): 
print('Name:',self.name) 
class Dob: 
def __init__(self): 
self.dd=10 
self.mm=5 
self.yy=1947 
def display(self): 
print('Dob={}/{}/{}'.format(self.dd,self.mm,self.yy)) 
p=Person() 
p.display() 
x=p.db 
x.display()

Output

PowerShell
Name: durga
Dob=10/5/1947

Example

  • Inside a class we can declare any number of inner classes.
Python
class Human: 
 
def __init__(self): 
self.name = 'Sunny' 
self.head = self.Head() 
self.brain = self.Brain() 
def display(self): 
print("Hello..",self.name) 
 
class Head: 
def talk(self): 
print('Talking...') 

class Brain: 
def think(self): 
print('Thinking...') 
 
h=Human() 
h.display() 
h.head.talk() 
h.brain.think() 

Output

PowerShell
Hello.. Ajay
Talking...
Thinking...

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error