Python package 1

Python import class

Introduction for importing class

Module

One file is handled as one module. We can import module using import.
To import class, method, etc…, use module.xxxx

package

We can get together

Same directory

Import same directory file module

|-test.py
|-main.py

test.py

class testclass:

    def __init__(self):
        print("this is test class")

    def testmethod(self, str):
        print("this is test method")
        print(str)

main.py

if __name__ == "__main__":

    import test
    testclass1 = test.testclass()
    testclass1.testmethod("Hello World!")

    from test import testclass
    testclass2 = testclass()
    testclass2.testmethod("Test class")

filename is module name.

Create directory for package

|-calc
   |- __init.py__
   |- calc.py
|-main.py

calc.py

def add(val1, val2):
    return val1 + val2

only one method

main.py

import calc.calc
print(calc.calc.add(1,2))

Can access directory(package name). module name(file name)
__init.py__ is package initialization python script.
If this file exists under the directory,

Deep directory structure

|-math
    |- abs
        |- __init__.py
        |- calccabs.py
|- main.py

Next is deep directory structure
We can add python reading path with sys.path.append(path)
main.py


path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "math")
sys.path.append(path)
import abs.calcabs
print(abs.calcabs.fabs(11))

path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "math/abs")
sys.path.append(path)
import calcabs
print(calcabs.fabs(-10))

To add path, we can import module.