Writing your own python modules

Here in this post I will be helping you with writing your own custom modules. Well module is a python file with .py extension. The module can have class definitions, function definitions. Lets start by creating one. Lets create a file mymodule.py with a fovourite text editor, mine is 'geany'. And lets write the following function in it.
def hello():
print "Hello Function"


And save it. We have successfully created a module here. Lets use the module. Open your python interpreter in the directory where your python module is. And then import the module using
import mymodule
and to use the function use
mymodule.hello()
This should print
Hello Function
on your screen. The function only can also be imported as
from mymodule import hello
and the function can be called as
hello()
. i.e. no need to use the module name any more.
Not only function but also the modules can have class definitions. Lets take at the following example. Create a new module mymodule1.py and write the following code in it.
class Testclass:
var="test class has variables too"

def __init__(self):
pass

def fun1(self):
print "fun1() function of Test Class"

def fun2(self):
print "fun2() function of Test Class"
and save it. Now to use this module we can use the same above method to import it i.e.
import mymodule1
and then we can create objects of the class, call functions and so on.
>>> import mymodule1
>>> testObject=mymodule1.Testclass()
>>> testObject.var
'test class has variables too'
>>> testObject.fun1()
fun1() function of Test Class
>>> testObject.fun2()
fun2() function of Test Class
>>>

Comments

Popular posts from this blog

Automate file upload in Selenium IDE

How To Install and Configure Nextcloud