Python Inner Class
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.
Let's 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.
Example of Python Inner Class
#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()
Example 2 of Python Inner Class
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)