Skip to content
Related Articles

Related Articles

Overriding Nested Class members in Python
  • Last Updated : 30 Jan, 2020

Overriding is an OOP’s (object-oriented programming) concept and generally we deal with this concept in Inheritance. Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

Let’s consider a real-life example, where genes are embedded with traits for the next generation and every generation has their own traits which they transfer to the other generations with the help of Genes. Here we take a Genes class and one nested class Trait. Trait class has some traits like walk, hair and disease, and their values. These Genes will transfer to child class and child class may have some traits of its own and some inherit from its parent. This functionality can be implemented with the help of overriding nested class members.

Example:




# Genes are like messages in human 
# body which transfers from parent to 
# child. Same thing we have used here
# to show the real implementation of 
# above concept in python.
  
class Genes:
      
    # Inner class
    class Trait:
        walk ='Fast'
        hair ='Black'
        disease =('Diabetes', 'Migraine', 'TB')
  
class child(Genes):
      
    # Inner class
    class Trait(Genes.Trait):
        walk ='Fast'
        hair ='Black'
        disease =('Typhoid', ) + Genes.Trait.disease
          
          
# Driver's code
print(Genes.Trait.disease)
print(child.Trait.disease)

Output:

('Diabetes', 'Migraine', 'TB')
('Typhoid', 'Diabetes', 'Migraine', 'TB')>

Note: Use Nested classes only if it is necessary, otherwise it will only make your code complex and difficult to debug.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :