Monday 27 January 2020

Packages


Package

A package is basically a directory with Python files and a file with the name __init__.py(double underscore before init and after init). This means that every directory inside of the Python path, which contains a file named __init__.py, is treated as a package by Python. We can put modules into a Package.

Steps to create packages:


1.    Create any folder (directory), that folder (pack) is treated as a package, name it as any name preferably give a related name which suits to your project. Ex: pack1
2.    Then we need to create modules, generally, we put the classes and the required functions in it.
3.    Go to that package (i.e pack1)
4.    Finally we create an __init__.py file inside the directory i.e package, to let Python know that the directory is a package. So Create one empty file __init__.py, save in  that folder ex: pack1
__init__.py
5.    Write any python file example module1.py
#module1.py
def f1():
    print("module1 from pack")

6.    Save this code in that package “pack1” folder
7.    Come out of that pack1 folder
8.    Create one python file to test the above package i.e test.py
#test.py
import pack1.module1
pack1.module1.f1()

"""output:
module1 from pack"""
9.    Another way to use packages

#import pack1.module1
from pack1.module1 import f1
#pack1.module1.f1()
f1()

"""output:
module1 from pack"""

By using Pycham:

1.    Open Pycharm software
2.    Go to file ànew Projectàmyproject (You can give any name)
3.    Place the mouse on the myprojectàright clickàcreate Python package
4.    Given any name to your package i.e mypack

By using Pycharm:
1.      Open Pycharm software
2.      Go to fileàchoose new-àselect new projectà”you can give any name for you project. Ex: myproj
3.      Place the mouse on the ‘myproj’àright clickàchoose create python package i.e pack1
4.      Write any python file under pack 1 example module1.py
   #module1.py
   def f1():
       print(“module1 from pack”)
5.      Save this module1.py in that package i.e pack1 folder
6.      Come out of that pack1 folder, i.e place the mouse at your project name: i.e myproj, right clickànewàclick on python file, give the python file name i.e test.py
7.      Create one python program or file to test the above package.
#test.py
 import pack1.module1
 pack1.module1.f1()
or
import pack1.module1 as r
 r.f1()
Execute this test.py program


Next: Exception Handling

Prev:The special variable __name__
https://youtu.be/DZpN8_7i9l8

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...