Wednesday, May 13, 2020

modules in python

Modules : To organize the code logically.

( In simple language, dividing a large file into small files ).
( modules takes the help of the files ).
( it uses files to implement this modules concept ).

filename = modulename 



The variables and methods in file1.py module can be used by the file2.py module and vice-versa.






To import that, we are using the import statement.

sometimes file2.py module, wants only a particular or methods from file1.py module for that,

we can use a keyword called "from"

from file import x


"it will be helpful for the developer in the maintainence perspective".

( This will increase productivity ).

Examples:





first-attempt-error



corrected the second.py 


result



How to access a specific variable or method ?/ how to import part of the code ?




Note : 

1. set of code, when we are organizing logically called modules.
2. one module can access another module.
( the modules will have shared parameters through that, it can be able to organize ).


For the second module, I want to give only access to x=10;

How to import part of the code ?

from <modulename> import x 







Packages:

Collection of related modules.

( if you store related modules in to a container are called packages ).



for example,

In a project, we have 10 modules

first 5 modules        >  one related 
second 5 modules   >  one related 

related modules we can create into one package.


Advantages:

1. when related modules in to one package, will make the accessing very fast
2. we can also avoid name collisions.


How you can give a some module name ?

it is not possible in one package.
we can give some module name in two different packages.




Example : 



Description 


college is a package 

college/

( In every package, we have a initialization method ) 

__init__.py
branches.py

Inside the college, we may have one more package called branch ( sub-package ).

branch/

__init__py__.py
students.py
staff.py

(this will make access very easy).


How to import the modules under sub-packages ?

import college.branch.students

or 

from college.branch.students import name 




























No comments:

Post a Comment