In the last 3 weeks, we have been given a preview of the whole course and have mainly focused on Classes, stacks, raising Exceptions and recursion. I have no experience in programming before entering the university, so all of knowledge is based on what I had learned in last term's CSC108 course. Despite the fact that I'm not so proficient with programming compared to some of my peers who have already been exposed to Java or C before, I found it not hard to catch up after the winter hiatus.
So this week, I will talk about one of the most crucial part of Python: Object Oriented Programming (aka OOP). We can in a way say that the whole design philosophy of Python is a clean programming style. And I learnt several lessons last term which resulted in deduction of marks due to my bad format. The PEP8 documents on the course website really helped me a lot with respect of the style standards when programming. Also attending tutorials let me learn more about procedural style of programming.
Back to the topic, OOP really has valuable usefulness because it eliminates the unnecessary code and increase the its efficiency. It greatly enhanced the programs flexibility, compatibility and makes the program much more simple to maintain. For example, if we want to write a set of if statements including calling other functions:
if value == 'one':
# do something
function1()
elif value == 'two':
# do something else
function2()
elif value == 'three':
# do something else
function3()
However we can achieve the same goal by using OOP and ends up in shorter lines:
def function1():
print 'You chose one.'
def function2():
print 'You chose two.'
def function3():
print 'You chose three.'
#
# switch is our dictionary of functions
switch = {
'one': function1,
'two': function2,
'three': function3,
}
#
# choice can eithe be 'one', 'two', or 'three'
choice = raw_input('Enter one, two, or three :')
#
# call one of the functions
try:
result = switch[choice]
except KeyError:
print 'I didn\'t understand your choice.'
else:
result()
print 'You chose one.'
def function2():
print 'You chose two.'
def function3():
print 'You chose three.'
#
# switch is our dictionary of functions
switch = {
'one': function1,
'two': function2,
'three': function3,
}
#
# choice can eithe be 'one', 'two', or 'three'
choice = raw_input('Enter one, two, or three :')
#
# call one of the functions
try:
result = switch[choice]
except KeyError:
print 'I didn\'t understand your choice.'
else:
result()
The magic happens in the line result = switch[choice] which returns one of our function objects (or raises a KeyError).
This is just one very crude example from the site (http://www.voidspace.org.uk/python/articles/OOP.shtml) to show the advantages of OOP. And as we learn more in the following weeks, I'm sure that the importance of knowing OOP will be more apparent.