Module or Package in Python
Package in Python
Package is nothing but a group of files or classes or modules. When there are a large number of modules, it is required to organize them into package. We can put same functionality modules/classes in a one directory.
Working with Python
packages is really simple. All you need to do is:
1. Create a directory and
give it your package's name.
2. Put your classes in it.
3. Create a __init__.py file
in the directory
Example:
1.
Create a dictionary Person
2.
Now add classes to package. Student.py
and Employee.py
Student.py
class Student:
def
__init__(self):
''' Constructor for this class. '''
#
Create some member student
self.members = [1,"Piyush"]
def
studData(self):
print('Printing Student Information')
for member in self.members:
print('\t%s ' % member)
Employee.py
class Employee:
def
__init__(self):
''' Constructor for this class. '''
#
Create some member employee
self.members = ["E1","Piyush", "Rajkot"]
def
empData(self):
print('Printing Employee Information')
for member in self.members:
print('\t%s ' % member)
3.
Create a __init__.py file
in the directory Person. Currently put empty file.
That's it! For testing, we create a simple file named
test.py
in the same
directory where the Person
directory
is located. We place the following code in the test.py
file.
# Import classes from your brand new package
from Person.Student import Student
from Person.Employee import Employee
# Create an object of Student class & call a
method of it
s1= Student()
s1.studData()
# Create an object of Employee class & call
a method of it
e1 = Employee ()
e1.empData()
Output:
Printing Student
Information
1
Raj
BCA
Printing
Employee Information
E1
Piyush
Rajkot
Comments
Post a Comment