Python Inner classes

Writing a class within another class is called creating an inner class or nested class (or) declaring or defining a new class structure within existing python class structure is termed as a python inner class or nested class to the existing class.

For example, if we write class B inside class A, then B is called python inner or nested class, Inner classes are useful when we want to sub group the data of a class.

Inner class example:

Let us take a person's data like name, age, date of birth etc. Here, name contains a single value like 'Karthik', age contains a single value like '30' but the date of birth does not contain a single value. Rather, it contains three values like date, month, and year.

So, we need to take these three values as a sub group. Hence it is better to write date of birth as a separate class as a Dob inside the Person class. This Dob will contain instance variables dd, mm and yy which represent the date of birth details of the person.

class Person: 
   def __init__(self): 
     self.name = 'Karthik' 
     self.db = self.Dob() #this is Dob object

A Python program to create Dob class within Person as its inner class.

CopiedCopy Code
#inner class example 
class Person: 
   def __init__(self): 
       self.name = 'Karthik' 
       self.db = self.Dob() 
   def display(self): 
       print('Name=', self.name) 
   class Dob: 
    def __init__(self): 
      self.dd = 10 
      self.mm = 5 
      self.yy = 1988 
    def display(self): 
       print('Dob= {}/{}/{}'.format(self.dd, self.mm, self.yy)) 
p = Person() 
p.display() 
x = p.db 
x.display()

A Python program to create another version of Dob class within Person class.

CopiedCopy Code
class Person: 
   def __init__(self): 
      self.name = 'Rajesh' 
   def display(self): 
      print('Name=', self.name) 
   class Dob: 
      def __init__(self): 
         self.dd = 10 
         self.mm = 5 
         self.yy = 1988 
      def display(self): 
          print('Dob= {}/{}/{}'.format(self.dd, self.mm, self.yy)) 
p = Person() 
p.display() 
x = Person().Dob() 
x.display() 
print(x.yy)