Part-III - Python: Object Oriented Programming
In part-II of this series, we saw how inheritance works when we derive from a single base class. In part-II, the base and derived classes were all declared in the same file. In this article, we look at how classes can be declared in their own files and how they reference each other. The ability to reference source code in multiple files is a very important requirement towards building complex scalable applications.
Our project solution will the have following 3 files:
Python | C# | Comments |
---|---|---|
CBaseMath.py | CBaseMath.cs | Base class code |
CAdvancedMath.py | CAdvancedMath.cs | Derived class code |
Program.py | Program.cs | Code to instantiate and call functions |
The code for each of these files is given below:
CBaseMath.py / CBaseMath.cs
Since CBaseMath is a base class it does not need to reference other classes. The definition for next class will reference CBaseMath and note the difference in classes residing in different source code files are referenced.
CAdvancedMath.py / CAdvancedMath.cs
Note the important line from CBaseMath import CBaseMath in the Python code. This tells the Pythong interpreter to load the class CBaseMath from the file 'CBaseMath.py'. In C#, since both CBaseMath and CAdvancedMath are in the same namespace we do not need to add an explicit reference to load CBaseMath. The same syntax will be used in 'Program.py'.
Program.py / Program.cs
Since we are instantiating only the CAdvancedMath class, we need access only to the 'CAdvancedMath.py' file. This is achieved by the from CAdvancedMath import CAdvancedMath declaration. As before due to same namespaces, C# does not need an explicit declaration to include CAdvancedMath.
The outputs for the respective code bases is given as:
The following screen shows the PyCharm and Visual Studio IDE's with the solution containing this code.
As we can see from the screen captures, the multiple files are listed in the project tree.
Comments
Post a Comment