Implementing Java Interfaces in Jython

Saturday, September 27, 2008

Implementing Java Interfaces is a common task where different java classes implement the interface methods according to their design behavior, however I was curious to learn how to implement java interfaces from jython, though you cannot vaguely call that a certain jython class implements a java interface because of the rules to which interfaces are bound to in java, one can say that a jython class implementing a java interface is something similar to a jython class extending a java class whose methods are not defined in java and the jython class need not necessarily implement all methods which the java interface defines because of the nature of which jython script works as we will see below.

An Interface in java is a class which declares certain methods which SHOULD be DEFINED by all implementing java classes, but when you implement a java inferface from jython, it doesn't serve much purpose as it merely means defines a similar method in jython class which is declared in java interface without adhering to any rules which apply to java interfaces, therefore the only application which I may think of using java interfaces from jython is in cases where one needs to access some constants defined in the java interface or defining similar methods of the java interface for which an equivalent implementation class was not provided in java. The below example will make things clear.



//
// JavaInterface.java
// Author: S.Prasanna
// A Simple java interface
//

public interface JavaInterface {

Object add(Object a, Object b);

void multiply(Object a, Object b);
}
1
2
3
4
5
6
7
8
9
10
11
12

Listing 2: JythonImpl.py


#
# Implementing Java Interface from jython
# JythonImpl.py
# Author: S.Prasanna
#

import JavaInterface
import traceback

class JythonImplA(JavaInterface):
""" Class JythonImplA implementing JavaInterface """

def __init__ (self):
print "This is JythonImplA class which implements a java interface"

def add(self, a, b):
return a + b

class JythonImplB(JavaInterface):
""" Class JythonImplB implementing JavaInterface """

def __init__ (self):
print "This is JythonImplB class which implements a java interface"

def add(self, a, b):
return a + b

def multiply(self, a, b):
return a * b

if __name__ == "__main__":

jythonClassA = JythonImplA()
print "JythonClassA add method output 10 + 20 =", jythonClassA.add(10,20)

try:
jythonClassA.multiply(10, 20)
except:
print
traceback.print_exc()

try:
jythonClassA.multiply(10, 20, 30, 40)
except:
print
traceback.print_exc()

try:
jythonClassA.divide(20, 10)
except:
print
traceback.print_exc()

print
jythonClassB = JythonImplB()
print "\nJythonClassB add method output =", jythonClassB.add(10, 20)
print "JythonClassB multiply method output 10 * 20 =", jythonClassB.multiply(10, 20)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

Output:

C:\>jython JythonImpl.py
This is JythonImplA class which implements a java interface
JythonClassA add method output 10 + 20 = 30

Traceback (most recent call last):
File "JythonImpl.py", line 37, in ?
jythonClassA.multiply(10, 20)
AttributeError: abstract method "multiply" not implemented

Traceback (most recent call last):
File "JythonImpl.py", line 43, in ?
jythonClassA.multiply(10, 20, 30, 40)
TypeError: multiply(): expected 2 args; got 4

Traceback (most recent call last):
File "JythonImpl.py", line 49, in ?
jythonClassA.divide(20, 10)
AttributeError: divide

This is JythonImplB class which implements a java interface

JythonClassB add method output = 30
JythonClassB multiply method output 10 * 20 = 200

Explanation:

The java interface class has two methods which defines two methods add and multiply which takes two java Objects and returns a java Object. Note that the return type of multiply method is void or in other words, the multiply method doesn't return any value.

The jython script JythonImpl has two classes JythonImplA and JythonImplB which implement the java interface, note that the syntax for both inheritng and implementing a class in jython are the same as shown below.

class JythonImplA (JavaInterface):
class JythonImplB (JavaInterface):

Lines 9 - 17 Here the JythonImplA class defines only the add method, which is declared in the JavaInterface, though it should not be called as defining a java interface method, but its an add method which the JythonImpl overrides.

Lines 18 - 29 Here the JythonImplB class defines two methods add and multiply, which are declared in the JavaInterface, again these methods are jython class methods and not necessarily an implementation of the java inteface methods, see the return type of the multiply method in JythonImplB, it returns the product of two integers, whereas the java interface method defines void as the return type.

Lines 32 - 34 Here we instantiate JythonImplA and call its add method, though it did not define multiply method, its still perfectly legal as the method it defines has nothing to do with complying with java interface rules.

Lines 35 - 40 Here we try to call the multiply method of JavaImplA class which it doesn't define, note that since in this case there is no implementation of multiply method in JythonImplA, therefore it tries to call the SuperClass method, since the superclass JavInterface doesn't provide any implementation of multiply method, you will get an exception

AttributeError: abstract method "multiply" not implemented

Similarly when multiply is called with four parameters as in line 42, you will get an exception

TypeError: multiply(): expected 2 args; got 4

Because the multiply method in the superclass takes only two methods (but not implemented).

Lines 47 - 51 Here we try to call a non existent method divide and since even the superclass doesn't declare such a method, we will get an attribute error.

Lines 53 - 57 Here the JythonImplB class defines both the methods add and multiply which the superclass also declares, therefore you will get the expected output (note that the superclass method signature for the multiply method is different from what jython defines which returns the product of the two numbers).

In a nutshell when you say a Jython Class Implementing a Java Interface its ....

1. The Jython class simply extends a java class which has no method definitions (or the super class has only method declarations and defines constants)

2. As obvious, the jython class need not define all methods declared in the java class, but when it defines, its a jython class method which need not have the return types and arguments to match that of the java interface, its more or less a method overriding in jython.

3. When a jython class instance tries to access a method which is not defined in the jython class but declared in the super class (the java interface), you will get an error AttributeError: abstract method "methodname" not implemented since the java interface doesn't have any implementation of that method.

The only application where you need to implement a java interface from jython is when there is no implementing class in java or you need to access some constants defined in the corresponding java interface.

Download, Installation and Configuration of Microsoft JVM (MSJVM)

Thursday, September 25, 2008

This writing will explain how to install and configure Microsoft Java Virtual Machine in IE 7 (MSJVM). Microsoft Java Virtual Machine, though has reached its end of life, is still being used by lots of applications to get live data through Internet Explorer, especially live stocks/equity related applications.

From my experience though installing Microsoft Java Virtual Machine is an easy task, one also needs to enable some add ons to make it work, in fact I was hitting the wall sometimes without proper configuration and I hope this writing will make the installation and configuration part simple. The following was tested in Internet Explorer 7 although it may be applicable for previous versions. Here we go..

1. Download Microsoft Java Virtual Machine (MSJVM) from any of the sites mentioned in this page.

2. Download Microsoft JVM removal tool also which will be handy in case you need to remove/uninstall Microsoft JVM.

3. Now once you have installed MSJVM, you need to restart the system, upon rebooting make sure you have Microsoft VM enabled as shown in the figure below (in IE Tools -> Internet Options -> Advanced -> Check Microsoft VM is installed)


Figure 1:
After installation of Microsoft JVM

4. Enable Microsoft JVM add-ons.

If after step 3, you are still having problems with running MSJVM applets (.cab files), then probably you need to enable the Microsoft Web Browser Applet Control add-on.

In IE go to Tools -> Manage Add-ons -> Enable or Disable Add-ons -> Select Add ons that have been used by Internet Explorer from drop down menu, click Web Browser Applet Control (Corresponding to Publisher Microsoft Corporation), and check enable, then restart the browser, see the figure below.


Figure 2:
Enabling Web Browser Applet Control Add-on (Corresponding to Publisher Microsoft Corporation)

5. Once you have executed steps 3 and 4, your Microsoft JVM would work successfully in IE (if you already have other JVM enabled, say Sun Java Virtual Machine, you can now switch between the two as shown below).

6. Switching or Changing from Microsoft Java Virtual Machine to Sun Java Virtual Machine :

In case you already have other JVM installed, you can uncheck that in IE, for example in some cases you may need to have Sun JRE to run Sun Java applets and other java related plugins and in some cases you may need to use Microsoft JVM, you can alternate between the two (In IE, go to Tools -> Internet Options -> Advanced -> Check/Uncheck Java or Microsoft VM option), see the below figure.

Figure 3: Changing between Microsoft JVM and Sun JVM

7. Switching or Changing from Sun Java Virtual Machine to Microsoft Java Virtual Machine :

Though you can uncheck Sun Java Virtual Machine and enable Microsoft JVM as in the previous figure to switch from Sun JVM to Microsoft JVM, sometimes I have encountered problems in running MSJVM after unchecking Sun Java Virtual Machine and restarting IE, to solve this problem you need to enable Web Browser Applet Control (Corresponding to Publisher Sun Microsystems), not sure about the logic behind this, but its needed as shown in the figure below.

In IE go to Tools -> Manage Add-ons -> Enable or Disable Add-ons -> Select Add ons Currently loaded in Internet Explorer from drop down menu, click Web Browser Applet Control (Corresponding to Publisher Sun Microsystems) and check enable, now you can run Microsoft Java Virtual Machine after restarting the browser, see the figure below.

Figure 4: Enabling Web Browser Applet Control Add-on (Corresponding to Publisher Sun Microsystems)

Jython Online References and Books for Java/Python Programmers

Wednesday, September 24, 2008

Ever since I introduced jython to some of my friends, I found that there is no one stop comprehensive jython reference list which will make life easy for a jython programmer, especially a beginner. For newbies, jython is an implementation of CPython language in JVM through which one can access java classes in addition to standard python modules.

Since the idea of implementing scripting languages in java is now being explored rapidly than ever, its better to have some JVM scripting skills in the kitty, for those who prefer scripting, they can use java the way they want to without much hiccups in learning java completely to start with, for java programmers, scripting on JVM would ease out compexity of some mundane tasks which need not be so tightly bound to java (like unit testing). Even though there are other scripting flavours of jython like JRuby, Groovy, Rhino, Jacl, Beanshell, etc, I prefer jython, though it depends on the scripting language you are comfortable with, the choices are limitless.

One more good thing is renowned IDEs like Netbeans also have jython support, so java programmers need not come out of their favorite IDE to code in jython.

So where would jython be useful? I have used it for server side programming and unit testing till date, though there are lots of applications of jython ranging from testing to database to GUI programming, in fact it wouldn't be an over statement to say that jython has good reach like its counterpart CPython with useful applications developed in it.

Here are some useful references for you to start with. The below are some useful online references, which I have found useful, we will come to books later.

Jython Online and Book References:

1. Jython Introduction Part1 and Part2 by Barry Feigenbaum, from www.jython.org, the home page of jython (Make sure you first visit the old jython site, some visitors could easily get lost with vital resources which the old jython page provides, no its not obsolete).

2. Server side programming in jython: For beginners and advanced programmers.

3. Jython Unit testing tutorial, for those who are interested in writing unit tests in jython.

4. Jython Swing basics, introduction to GUI Programming in jython.

The below are some very useful jython book references (and my favorite ones too) which will explain all concepts of jython from a java as well as python programmers's perspective, its worth having it in the bookshelf, thanks to Google books as well.

1. Jython for Java Programmers.

2. Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython.

3. Jython Essentials.

(List to be extended).

More to come from my side too, keep watching.


Passing and returning Java Arrays from Jython

Friday, September 19, 2008

Accessing java arrays from jython is a little tricky task because one can't assign arrays in a similar way in jython as it would be done in java. Therefore in order to pass an array from jython to java and access an array returned from java in jython, one should use the jarray module.

If you are new to jython, for a customary introduction, jython or JPython is an implementation of Python programming language in JVM, using jython one can directly access java classes and its attributes in addition to the standard python modules. Jython has applications in Unit testing, Server side programming, etc.

In this section we will explore jython arrays using a simple code which will create a java String array from jython, pass the string array to java class which will append an element to the String array and return the updated array to jython which will be printed. So simple isn't it, lets look at the code.


Listing 1:
jythonArray.py


#
# Passing and returning java arrays from jython
# jythonArray.py
# Author: S.Prasanna
#

from java.lang import String
from jarray import array
import javaArray

inputArray = ["one", "two", "three", "four"]
jythonArray = array(inputArray, String)

print "Jython String Array =", jythonArray
print "\nAdding an string %s to jythonArray through javaArray class method...." %("five")
jythonArray = javaArray().append(jythonArray, "five")
print "\nJython String array after adding %s = %s" % ("five", jythonArray)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Listing 2: javaArray.java


//
// Manipulating jython arrays from java
// javaArray.java
// Author: S.Prasanna
//

public class javaArray {

public javaArray() {
}

//Append an element to to the input String array
public String[] append (String [] inputArray, String element) {
String [] appendArray = new String[inputArray.length + 1];

for (int i = 0; i < class="statement">return
appendArray;
}

public static void main (String args[]) {
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Output:

Compile the java class and execute the jython script in the same folder, the output will be

C:\> jython jythonArray.py

Jython String Array = array(java.lang.String,['one', 'two', 'three', 'four'])

Adding an string five to jythonArray through javaArray class method....

Jython String array after adding five = array(java.lang.String,['one', 'two', 'three', 'four', 'five'])

Explanation:

The java code (javaArray.java) is straightforward, it has an append method which adds the input String to the input String array and returns the result. Now we will come to the jython code.

Lines 6 - 12
from java.lang import String
from jarray import array
import javaArray

inputArray = ["one", "two", "three", "four"]
jythonArray = array(inputArray, String)
Here we import the array function from jarray module and then call the array function with a list of strings and the type of the array, here we mention the type as "String", similarly we can create array of any java objects by specifying the object class as second parameter. This is equivalent to the java code

String [] jythonArray = ["one", "two", "three", "four"]

Lines 13 - 17

We then pass the jython array to java class's append method where we append a String to the String array, then print the results. The line of importance here is
jythonArray = javaArray().append(jythonArray, "five")
where we instantiate a javaArray object and call its append method, note that creating an instance of a new java object is fairly simple in jython as we did above using javaArray().

A Quick Start Introduction to Python Programming - 5

Tuesday, September 16, 2008

In this concluding section (atleast for now), we will see more about object concepts in python and some introduction to python thread programming. From the last section on object oriented programming in python, I am sure that you would have understood something about class objects, instance objects and other OO concepts in python, an understanding of Object Oriented Programming in python is essential to explore the language further.

If you want to read this quick start introduction into python programming from the beginning, do visit "A Quickstart Introduction to Python Programming - 1".

As I always mentioned that everything in python is an object, it applies to everything like module attributes, functions, data types and infact importing a module in itself is an object which can be assigned to another python object as we will see below.


Listing 9:
object_concept.py


#
# Object concepts in python
# object_concept.py
# Author: S.Prasanna
#

import time

print "Todays date and time:", time.ctime(time.time())

print "time.time =", time.time
print "time.ctime =", time.ctime

# Get the time.time and time.ctime objects
timeobject = time.time
ctimeobject = time.ctime
print "Todays date and time:", ctimeobject(timeobject())

#Importing a module is also an object
timemodule = __import__("time")
print "Todays date and time:", timemodule.ctime(timemodule.time())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Todays date and time: Tue Sep 16 00:57:44 2008
time.time =
time.ctime =
Todays date and time: Tue Sep 16 00:57:44 2008
Todays date and time: Tue Sep 16 00:57:44 2008
>>>

Explanation:

Line 8 Here we print the current date and time using the time.ctime function which takes a floating point number as argument which the time.time() returns. Then we print the time.time and time.ctime objects which are built in functions in the time module.

Line 14 - 17 Here we assign the time.time and time.ctime built in functions to two objects, namely the timeobject and ctimeobject respectively and then print the current date and time in a similar way, this goes to show that objects and other built in functions are similar to variables which can be assigned to other objects just as we assign primitive data types to variables.

Line 18 - 21 As I mentioned earlier importing a module is also an object, if you want to access the imported module, use the __import__ built in function which will return the imported module, then one can simply call the methods and access other attributes of the module using the object to which the imported module is assigned.

So whatever we have seen till now are some interesting object oriented concepts in python, but its just a tip of the iceberg, there are lots to learn in this interesting language.

10. Thread Programming in Python

Python has good thread routines like other high level languages and I have discussed them in another article here.

What next....

So far we have learned about some important concepts in python, though this is a good start, there are lots of other interesting features of python one can learn from many valuable online resources. There are good free books on python available in web and I have listed my top three python programming books which you should look into to take your skills to the next level, of course I would also be writing more about this language in future.

A Quick Start Introduction to Python Programming - 4

Sunday, September 14, 2008

In this section, we will explore Object Oriented Programming in Python, we will see the differences between Python class objects and instance objects, public, private methods, inheritance, class variables, instance variables, __init__ functions, etc.

If you want to read this quick start introduction into python programming from the beginning, do visit "A Quickstart Introduction to Python Programming - 1"., I would recommend you to start from that section if you are a newbie as understanding OOPs concepts requires some foundation.

Python's class and object paradigms are little different from that of other high level languages like C++ and Java, if you are a hard core C++ or a java programmer your are bound to some surprises as I mentioned earlier, "Everything in Python is an Object" and this includes python classes too which in turn is a python object. Confused! So was I when I learnt this first, but its rather very simple to understand as we will see below.

Listing 8: oops.py


#
# OOPS concepts in python
# oops.py
# Author: S.Prasanna
#

import traceback

class Base:
def __init__ (self):
print "I am the base class's init"

def basemethod (self):
print "I am a base class method"

class Derived(Base):
# This is a class variable
classvar = 10

def __privatemethod (self):
""" This is a private method """
print "I am a private method, but I can still be accessed from outside"

def __init__ (self):
self.instancevar = 20
print "I am the super class's init"
Base.__init__(self)

def callbasemethod(self):
self.basemethod()

if __name__ == "__main__":

print "Derived class's class object:", Derived
print "Type of Derived's class object:", type(Derived)
print "Creating Instance od Derived class...."
derivedinstance = Derived()
print "Type of Derived's instance object =", type(derivedinstance)
print "Derived instance's class object =", derivedinstance.__class__

print "\nDerived class's classvar =", Derived.classvar
print "Derived instance's classvar =", derivedinstance.classvar # Same as Derived.classvar
print "Derived instance's instancevar =", derivedinstance.instancevar
print "Changing Derived's class variable classvar...."
Derived.classvar = 40 #Change Derived's class variable
derivedinstance.classvar = 50 #This becomes a new instance variable, won't change the class variable
print "Derived class's classvar =", Derived.classvar
print "Derived instance's classvar =", derivedinstance.classvar

try:
print "Trying to call a private method:"
derivedinstance.__privatemethod()
except:
traceback.print_exc()

print "Calling a private method using shortcut:"
derivedinstance._Derived__privatemethod()

print "Calling Derived's superclass method"
derivedinstance.callbasemethod()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Derived class's class object: __main__.Derived
Type of Derived's class object:
Creating Instance od Derived class....
I am the super class's init
I am the base class's init
Type of Derived's instance object =
Derived instance's class object = __main__.Derived

Derived class's classvar = 10
Derived instance's classvar = 10
Derived instance's instancevar = 20
Changing Derived's class variable classvar....
Derived class's classvar = 40
Derived instance's classvar = 50
Trying to call a private method:
Traceback (most recent call last):
File "C:\Prasanna\myblogs\prasannatech.net\entries\python_TOI\oops.py", line 52, in
derivedinstance.__privatemethod()
AttributeError: Derived instance has no attribute '__privatemethod'
Calling a private method using shortcut:
I am a private method, but I can still be accessed from outside
Calling Derived's superclass method
I am a base class method
>>>

Explanation:

Lines 8 - 14
class Base:
def __init__ (self):
print "I am the base class's init"

def basemethod (self):
print "I am a base class method"
Here we declared a Base class which has two functions namely __init__ and basemethod. The syntax for declaring a class is similar to that of declaring any other functions in python, except that we use a class keyword to declare a class.

The __init__ function is similar to a constructor (although its not) which will initialize any class/instance variables or other attributes of a class, the Base class declares another method which just prints a line.

Lines 15 - 30
class Derived (Base):
# This is a class variable
classvar = 10

def __privatemethod (self):
""" This is a private method """
print "I am a private method, but I can still be accessed from outside"

def __init__ (self):
self.instancevar = 20
print "I am the super class's init"
Base.__init__(self)

def callbasemethod(self):
self.basemethod()
Here we declare a Derived class which inherits the Base class. The syntax for extending a class is very simple as all we need to do is to mention the class to be extended inside the class declaration (inside the parenthesis).

We then declare a class level variable classvar = 10. Note that there are some differences between declaring a variable inside the __init__ function or any other methods inside the class and declaring above these methods at the class level. Now this variable is similar to a static variable in other languages like java with only one copy per class as we will see below. The __init__ function is used to initialize the class attributes, athough its similar to a constructor as in other languages like Java, C++, its actually not as the class object already exists before calling the __init__ method, but this method executes everytime one creates an instance of this type.

Then we define a private method __privatemethod, the syntax for declaring a private method is little different here, if we declare a method with __ before the method name, it will be interpreted as a private method. By default a private function cannot be accessed outside the class, but in python we can actually access this method as shown below (Python follows the philosophy Bad habits of OOPs ahould be avoided if not prohibited). The __init__ also defines an instance variable specific to the instance and initializes it.

We also declare a callbasemethod which will call the superclass's basemethod, also note that whenever we define __init__ method, we have to explicitly call the superclass's init method (Base.__init__ method).

Another thing of importance here is the self keyword which is a pointer (in abstract terms) to that specific instance of the class. The self parameter is used to specify that a method belongs to that instance of a class or in other words we should use self as the first parameter to all class functions, __init__ method and other variable assignments which belongs to that specific class instance.

Lines 31 - 60
if __name__ == "__main__":

print "Derived class's class object:", Derived
print "Type of Derived's class object:", type(Derived)
print "Creating Instance od Derived class...."
derivedinstance = Derived()
print "Type of Derived's instance object =", type(derivedinstance)
print "Derived instance's class object =", derivedinstance.__class__

print "\nDerived class's classvar =", Derived.classvar
print "Derived instance's classvar =", derivedinstance.classvar # Same as Derived.classvar
print "Derived instance's instancevar =", derivedinstance.instancevar
print "Changing Derived's class variable classvar...."
Derived.classvar = 40 #Change Derived's class variable
derivedinstance.classvar = 50 #This becomes a new instance variable, won't change the class variable
print "Derived class's classvar =", Derived.classvar
print "Derived instance's classvar =", derivedinstance.classvar

try:
print "Trying to call a private method:"
derivedinstance.__privatemethod()
except:
traceback.print_exc()

print "Calling a private method using shortcut:"
derivedinstance._Derived__privatemethod()

print "Calling Derived's superclass method"
derivedinstance.callbasemethod()
Here we print the derived class's object type and the derived instance's object type. Note that a class in itself is a python object of type "class" and an instance is another object of type "instance". Therefore the type of Derived would return (line 34) and type of the instance derivedinstance would return (line 37).

The statement derivedinstance = Derived() creates an instance of Derived and the instance's type would return , if we want to find the class associated with this instance, we use the __class__ attribute of derivedinstance which would print that instance's class object (line 39).

Now comes the interesting part, the Dervied class has a class level attribute classvar and we have an instance class of derived derivedinstance. Now if we want to print the class variable classvar, the below statements would print the same or in other words,

Derived.classvar = derivedinstance.classvar (both would print 10), this is also similar to other languages like java where a static variable can be accessed using the class name or the instance name qualifier. Now an interesting case comes when we try to change the class level variable in lines 45 and 46 using

Derived.classvar = 40
derivedinstance.classvar = 50

After the change Derived.classvar would print 40 and derivedinstance.classvar would print 50, how? This is because the statement

derivedinstance.classvar = 50 actually creates a new instance variable classvar and assigns it to 50 or put it in other way this is similar to creating a new instance variable in a method or in an __init__ statement of a class.

The statement derivedinstance.classvar = 50 is similar to self.classvar = 50 (self corresponds to that specific instance of Derived). This understanding is important when it comes to Object oriented programming in python.

Line 45 prints the instance variable instancevar of the class which is straightforward.

Lines 49 - 54 Here we try to access a private method of a class, which results in an exception (AttributeError).

Then we use the syntax
derivedinstance._Derived__privatemethod()
to access the private method, though its a bad practice its possible to do it in python.

In Line 60, we then access the superclass's method from the subclass.

To put in a nutshell....

1. A class in python is a python object of type class and an instance of a class is an object of type instance.
2. The __class__ attribute of an instance can be used to access the class corresponding to that instance.
3. The __init__ method of a class executes everytime an instance is created.
4. Python has private member functions, but they can still be accessed from outside or in other words, in sync with the philosophy "Bad OOP practices should be avoided, but not prohibited".
5. Class variables are declared above the methods and __init__ functions and instance variables are declared within class methods and start sith the self identifier.

In the next (concluding section) we will see more object concepts in python, some introduction to threads and other useful python references.

Continued here. A Quick Start to Introduction to Python Programming - 5.


A Quick Start Introduction to Python Programming - 3

Saturday, September 13, 2008

In this section, we will see some important built in functions like locals, globals and exception handling in python. If you want to read quick start introduction to python programming from the beginning, I would recommend you to visit "A Quickstart Introduction to Python Programming - 1".

6. Built in methods locals and globals

Put in a nutshell, the locals built in function will return a dictionary of all variables, methods and other data type names with their values as a key/value pair or all python object's and their attributes in the local namespace. Local namespace corresponds to all objects and their attributes within a python function or within a member function of a class. A global namespace corresponds to the module or all variables which are not in the local space are part of the global namespace at the module level.

The below example will make things clear.


#
# Locals Globals example
# locals_globals.py
# Author: S.Prasanna
#

import sys

def func():
""" A simple function to show locals, globals concept """
var1 = 10
print "Inside func, locals:", locals()
print "Inside func, globals:", globals()
print "Inside func, Printing the value of var1 in local namespace:", locals()["var1"]
print "Inside func, Printing the value of var1 in global namespace:", globals()["var1"]

if __name__ == "__main__":

var1 = 20
print "Inside main, locals:" ,locals()
print "Inside main, globals:" , globals()
print "\nInvoking function func...."

func()

print "\nInside main, Printing the value of var1 in global namespace:" ,var1
print "Inside main, Printing the value of var1 in local namespace:", locals()["var1"]
print "\nInside main, Invoking function func through globals:", globals()["func"]()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Inside main, locals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside main, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}

Invoking function func....
Inside func, locals: {'var1': 10}
Inside func, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside func, Printing the value of var1 in local namespace: 10
Inside func, Printing the value of var1 in global namespace: 20

Inside main, Printing the value of var1 in global namespace: 20
Inside main, Printing the value of var1 in local namespace: 20

Inside main, Invoking function func through globals: Inside func, locals: {'var1': 10}
Inside func, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside func, Printing the value of var1 in local namespace: 10
Inside func, Printing the value of var1 in global namespace: 20
None
>>>

Explanation:


Inside main, lines 18 - 22

It has to be noted that inside main, locals() = globals(), therefore both would return the same elements and attributes as shown in the output, both locals() and globals() prints all imported modules (sys), built-in functions, the name and value of var1 inside main, the function name func and its function object.

Then the function func is invoked, note that we have var1 in both main and in the function func.

Lines 8 - 15

Inside func, we invoke the locals() and globals() function, the locals() function prints all objects and their attributes in a key value pair, since the function func has only one local variable var1 = 10, it is printed. The globals() call in func would return the same as what globals() would return when invoked in global namespace (main).

We have var1 = 10 inside function func and var1 = 20 inside main, therefore inside func, both variables can be accessed using locals()["var1"] (would print 10) and globals()["var2"] (would print 20).

Lines 25 - 28

Coming back to main again, in line 25, we print the value of var1 which is 20, then we print the value of var1 through locals()["var1"] which would also print 20 because inside main locals() = globals(), therefore we cannot access var1 in function func, on the otherhand if we try to print any other variable inside func through locals (say var2 = 20 if initialized in func), an exception will be thrown if there is no similar variable in main to override.

Finally we invoke the function func again, now through globals()["func"], which would invoke the function object.

7. Exception handling

Exception handling in python is similar to that of other Object Oriented Programming languages, here we use try and except statements to execute some statements and catch exceptions if any, however the try block also has an optional else part which we can see below.

Listing 7: exceptions.py


#
# Exception handling in python
# exceptions.py
# Author: S.Prasanna
#

import sys
import traceback

try:
open("Non-existentfile.txt", "r")
except IOError:
# Handle specific exception IOError
print sys.exc_info()[1]

try:
a = 10/0 #This would result in ZeroDivisionError
b = "Hello" + 10 #This would result in TypeError
except TypeError:
# Specific exceptions should be handled first
print "TypeError in assignment."
traceback.print_exc()
except:
# Handling generic exceptions
print "An exception occured in evaluating 10/0."
traceback.print_exc()

try:
count = 10
except:
# In case of an exception, this block will execute
print "An exception occured in try block."
traceback.print_exc()
else:
# In case of no exception, the else part will execute
print "Value of count = " , count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
[Errno 2] No such file or directory: 'Non-existentfile.txt'
An exception occured in evaluating 10/0.
Traceback (most recent call last):
File "C:\Prasanna\myblogs\prasannatech.net\entries\python_TOI\exceptions.py", line 17, in
a = 10/0 #This would result in ZeroDivisionError
ZeroDivisionError: integer division or modulo by zero
Value of count = 10
>>>

Explanation:

Lines 10 - 14

Here we have two blocks, the try and the except block, in the try block we try to open a non existent file (an invalid file name is used for the same), which would throw an exception (IOErrror), which is caught in the except block, note that the except block here catches a specific exception (IOError).

The sys.exc_info() returns a 3-Element tuple with more details related to the exception, the part we are interested is sys.exc_info()[1] which prints the error code [Errno 2] and the exception details (No such file or directory: 'Non-existentfile.txt').

Lines 16 - 26

Here we introduce two statements which will cause exceptions,

a = 10/0 #This would result in ZeroDivisionError
b = "Hello" + 10 #This would result in TypeError

The first statement would throw a ZeroDivisionError and the next statement tries to append a string with an integer which would result in a TypeError. In Line 19, we handle the TypeError and Line 23 handles generic exceptions (which would catcth any type of exception). Note always that specific exceptions should be caught first and then generic exceptions. In our case since the first exception is ZeroDivisionError, it will be caught by the second except statement which catches generic exceptions, then the traceback.print_exc() statement prints the complete details about the exception (with the exact line which caused the exception at the module level). Note that the output of traceback.print_exc() is same as what would be printed if you don't handle the exception (similar to other languages like java).

The traceback module has many useful diagnostic functions related to exceptions and it should be used for getting details about exceptions more frequently than sys.exc_info() .

Lines 28 - 36

Here we have a try - except block followed by an optional else statement, the except block will be executed when an exception is caught, otherwise the else part will be executed. The try block which initializes a variable doesn't throw any exception, as a result the else part gets executed.

We will see more about object oriented programming in python in the next section.

Continued here. A Quick Start to Introduction to Python Programming - 4.

A Quick Start Introduction to Python Programming - 2

Wednesday, September 10, 2008

In the previous introduction to python programming, we saw some basic datatypes in python, functions, conditional statements, importing modules, using functions like dir, accessing doc strings of modules/functions, etc. Again to reiterate its important to note that "Everything in python is an object", I don't mind saying this again, but when it comes to python world, this understanding is very important.

In this section we will see the differences between python and C modules and some special methods like lambda, filter and map functions in detail. If you are new to python programming, I recommend you to visit "A Quickstart Introduction to Python Programming - 1" before continuing this section.

4. Python and C (built in) modules
Although this is a simple concept, its worth understanding the differences between these two. The standard python modules may be of two different types, built in modules implemented in C or modules implemented in python. To see the difference, look at the following code.

Listing 4: modules.py



#
# Differences between Python and C modules
# modules.py
# Author: S.Prasanna
#

import sys, os
print "Details about Built in mudules and python modules"
print "Module sys type =", sys   # Built in module, implemented in C
print "Module os type =", os    # module implemented in python
1
2
3
4
5
6
7
8
9
10
11

Output:IDLE 1.2.2 ==== No Subprocess ====
>>>
Details about Built in mudules and python modules
Module sys type = 
Module os type = 
>>>
As one can see, module sys is a built-in module or in other words implemented in C and module os is a python module. One can also access C functions through python, for example python language doesn't have support for handling core system functions like managing device drivers or other important operating system routines, etc, in such a case one can use a framework like SWIG to interface python with C language and use those low level functionalities directly through python modules.

5. Special methods
Here we will discuss some special methods in python which will be convenient to handle repititive tasks.

Listing 5: special_methods.py



#
# Use of Lambda functions and special methods
# special_methods.py
# Author: S.Prasanna
#

# Example of lambda function
func = lambda x: x * x
print "%s square = %s" % (4, func(4))
print "%s square = %s" % (5, func(5))

def product(y): return lambda x: x * y

square4 = product(4)
square5 = product(5)

print "square4 =", square4
print "square5 =", square5

print "Product of 4 * 4 and 5 * 5 =", square4(4) * square5(5)
print "Product of 4 and 5 =", product(4)(5)

def filter_func (args):
""" A function which returns the remainder when a number is divided by 2 """
return args % 2

# Example of Filter function
list_input = [1,2,3,4,5,6,7,8,9,10]
list_output = filter(filter_func, list_input)
print "List contents =", list_input
print "Filter function filtered list output:" , list_output

# Example of Map function
list_input = [1,2,3,4,5,6,7,8,9,10]
list_output = map(filter_func, list_input)
print "List contents =", list_input
print "List output after map function:" , list_output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

Explanation:

Lines 6 - 12:

Line 7 defines a lambda function like func = lambda x: x * x.

Lambda functions are something like anonymous inline functions which doesn't take take parameters similar to a normal function and don't have return values. The return value of a lambda function is the result of the expression in the lambda function. Here we define a lambda function which computes the product of a number multipled by itself, therefore func(4) will be 4 * 4 = 16 and func(5) = 25 (Lines 9 to 10).

Line 11 defines another function which inturn returns a lambda function,

def product(y): return lambda x: x * y
in other words, when we say square4 = product (4) (line 13) it is similar to this

square4 = lambda x: x * 4 (4 is the first parameter we supply to product function)
Simlarly square5 = product(5) means, square5 will have a lambda function square5 = lambda x: x * 5

Line 16 and 17 confirms that square4 and square5 are lambda functions.

Therefore square4(4) will inturn invoke the returned lambda function which will compute (and return) 4 * 4 and square5(5) will return 5 * 5, therefore square4(4) * square5(5) will be (4 * 4) * (5 * 5) = 400

Similarly product(4)(5) will be 20 because product(4) will return a lambda function lambda x: x * 4 and 5 will be used as the paramater to invoke the returned lambda function (which is anonymous), therefore computing 4 * 5.

Lines 22 - 31:

Line 22 defines a function filter_func which returns the remainder of a number when divided by 2 (divisible by 2 check).

Lines 26 - 31
# Example of Filter function
list_input = [1,2,3,4,5,6,7,8,9,10]
list_output = filter(filter_func, list_input)
print "List contents =", list_input
print "Filter function filtered list output:" , list_output
The filter function takes a function name and a list as input parameters and returns a list with the input numbers for which the filter function returns a true value (A true value in python is any integer which is > 0). Since in the above filter function, filter_func =0 for all even numbers (it computes mod 2), therefore the list will have only odd numbers [1,3,5,7,9]

Lines 32 - 37:

# Example of Map function
list_input = [1,2,3,4,5,6,7,8,9,10]
list_output = map(filter_func, list_input)
print "List contents =", list_input
print "List output after map function:" , list_output
The map function takes a function name and a list as input parameters and returns a list with the return values of the input function applied to each element in the input list.Therefore for the above list, the return value would be the remainder after the number divided by 2, which will be [1, 0, 1, 0, 1, 0, 1, 0, 1, 0].

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
4 square = 16
5 square = 25
square4 = at 0x01ED6070>
square5 = at 0x01E72F70>
Product of 4 * 4 and 5 * 5 = 400
Product of 4 and 5 = 20
List contents = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filter function filtered list output: [1, 3, 5, 7, 9]
List contents = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List output after map function: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
>>>
4 square = 16
5 square = 25
square4 = at 0x01DFB8B0>
square5 = at 0x01ED6070>
Product of 4 * 4 and 5 * 5 = 400
Product of 4 and 5 = 20
List contents = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Filter function filtered list output: [1, 3, 5, 7, 9]
List contents = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List output after map function: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
>>>

Continued here. A Quick Start to Introduction to Python Programming - 3.


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.