Overriding Nested Class members in Python

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.