Welcome to another Python article on Subclasses / Superclasses. I will also get into Ovewrite Variable on Sub as well as Multiple Parent Classes. Here is a mind map of all articles related to Python.
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part 2 – Modules and Functions, Strings
- Starting up with Python – Part 3 – Sequences and List, Slicing and Editing
- Starting up with Python – Part 4 – More list functions and Slicing lists
- Starting up with Python – Part 5 – Methods
- Starting up with Python – Part 6 – Sort and Tuples, Strings and stuffs, methods and Dictionary
- Starting up with Python – Part 7 – If statement, Else and elif statements
- Starting up with Python – Part 8 – Nesting and Comparison operators
- Starting up with Python – Part 9 – And and Or operators
- Starting up with Python – Part 10 – While, For, Infinite and Break Loops
- Starting up with Python – Part 11 – Building functions and Default parameters
- Starting up with Python – Part 12 – Multiple Parameters, Parameter Types and Tuples as Parameters
- Starting up with Python - Part 13 - Object Oriented Program and Classes and Self
This is interesting when you can inherit a single parent class from a class.
>> class parentClass: ... var1="country" ... var2="region" ... >>> class childClass(parentClass): ... pass ... >>> parentObject=parentClass() >>> parentObject.var1 'country' >>> childObject=childClass() >>> childObject.var1 'country' >>> childObject.var2 'region'
33. Overwrite Variable on Sub
We will now try to overwrite variable on subclass. I will create a parent class called hackers and the child class called project.
>> class hackers:... var1="country"... var2="age"... >>> class project(hackers):... var2="skills"
Let's access var2 from the parent and the child.
>> parentobject=hackers()>>> childobject=project()>>> parentobject.var1'country'>>> childobject.var2'skills
As we can see now if we try to overwrite its just by calling the variable in the class
This is cool if you have one huge class and if you want to change some few things in it.
34. Multiple Parent Classes
This is straight forward to use different items just by adding the name of your classes in your parameter.
>> class hackers:... var1="Mauritius"... >>> class skills:... var2="devops"... >>> class best(hackers,skills):... var3="we are hackers"... >>> childObject=best()>>> childObject.var1'Mauritius'>>> childObject.var2'devops'>>> childObject.var3'we are hackers'