Connecting modules in python

Previous
Next

Creating User module:

  • In our previous concepts, we have written the complete code in a single source file.
  • If the code is large, it is complex to analyze, understand and debug the code.
  • Large programs we simply divide into modules(Separate files)

arithmetic.py:

def add(a,b):
    c=a+b
    return c

def subtract(a,b):
    c=a-b
    return c

def multiply(a,b):
    c=a*b
    return c

calc.py:

import arithmetic

print("Enter 2 numbers :")
a = int(input())
b = int(input())

res = arithmetic.add(a,b)
print("Add result :",res) 

res = arithmetic.subtract(a,b)
print("Subtract result :",res)

res = arithmetic.multiply(a,b)
print("Multiply result :",res)

Why we need to call the function using module name even after import?

  • We can define members with same identity in different modules
  • We access the duplicate members from different modules by using the identity of module.

one.py:

def f1():
    print("one-f1()")
    return

def f2():
    print("one-f2()")
    return

two.py:

def f1():
    print("two-f1()")
    return

def f2():
    print("two-f2()")
    return

access.py:

import one
import two

one.f1()
one.f2()

two.f1()
two.f2()

Accessing classes from the Module:

  • A module is a collection of classes.
  • A class is a collection of variables and methods
  • To access the class members we need to import the module.

one.py:

class ABC:
    def m1():
        print("one-ABC-m1()")
        return

class XYZ:
    def m2(self):
        print("one-XYZ-m2()")
        return

access.py:

import one
class Access:
    def main():
        one.ABC.m1()
        obj = one.XYZ()
        obj.m2()
        return

Access.main()
Previous
Next

Add Comment

Courses Enquiry Form