Tutorial 02
Creating an User-Defined Python Package
Create a top level folder (e.g.:
ws) with the following sub-directory structuretutorials t02 calculator calculator_package
Open a console/terminal within the
calculatordirectory, activate the conda enviroment and start VS Code from the command line:
conda activate pta
code .
Using VS Code create the following files under their respective directories
./
calculate.py./calculator_package/
__init__.py./calculator_package/
calculator.py
In the
calculator.pycreate aCalculatorPython class:
class Calculator:
def get_version():
return "1.0.0"
def sum(self, val1, val2):
""" Sum of 2 values """
pass
def sub(self, val1, val2):
""" Subtract of 2 values """
pass
def mul(self, val1, val2):
""" Multiply of 2 values """
pass
def div(self, val1, val2):
""" Divide of 2 values """
pass
def exp(self, val1):
""" Return e raised to the power x """
pass
def sqr(self, val1):
""" Square root of a number """
pass
def ln(self, val1):
""" Natural log of a number """
pass
Content of
__init__.py:
__version__ = "1.0.0"
Content of
calculate.py:
from calculator_package.calculator import Calculator
if __name__ == '__main__':
try:
calculator = Calculator()
print(calculator.get_version()) ## it will fail, find out why
except Exception as e:
print(e)
In VS Code have as active open file
calculate.pyand from theRunmenu selectStart Debuggingto run the Python code.
Fix any issues and implement the Calculator functionality
Run
calculate.pyform the command line:
python calculate.py
Run
calculator.pyform the command line within thecalculatordirectory:
python calculator_package/calculator.py