Showing posts with label oop. Show all posts
Showing posts with label oop. Show all posts

Wednesday, April 20, 2011

How to create threads

The example show how to define the behavior of a thread and run it.
import threading
import time
import random

class MyThread(threading.Thread):
 def __init__(self, myName):
  threading.Thread.__init__(self)
  self.myName = myName

 def run(self):
  while True:
   time.sleep(random.randint(0,3)) # wait a random time from 0 to 3 secs
   print "My name is",self.myName

thread1 = MyThread("1")
thread1.start() # the thread will run in background
thread2 = MyThread("2")
thread2.start()
My name is 1
My name is 1
My name is 2
My name is 2
My name is 1
...
The two threads will print in the console their attribute myName with random time interval.

Tuesday, April 19, 2011

How to work with exceptions

Here is:
  • How to define an exception
  • How to raise an exception
  • How to catch an exception

class MyException(Exception): # a custom exception
 """ My own exception class """
 def __init__(self,value):
  self.value = value
 def __str__(self):
  return repr(self.value)

def myFunction(): # this function will raise a exception
 print "The shuttle is landed"
 raise MyException("Huston, we have a problem")

def handleException(): # this function will handle the exception
 try:
  myFunction()
 except MyException, e:
  print "Something is going wrong:", e.value

## test the exception handling ##
handleException();
The shuttle is landed
Something is going wrong: Huston, we have a problem

Monday, April 18, 2011

How to define a class (using inheritance too)

The snippet contains:

  • How to declare and use a class with attributes and methods
  • How to declare a class using inheritance

class Point2D:
 """ a point in a 2D space """
 name = "A dummy name" # attribute

 def __init__(self,x,y): # constructor
  self.x = x
  self.y = y

 def product(self,p): # method
  """ product with another point """
  return self.x*p.x + self.y*p.y

 def print_2D(self):
  print "(",self.x,",",self.y,")"

class Point3D(Point2D): # Point3D inherit Point2D
 def __init__(self,x,y,z):
  self.x = x
  self.y = y
  self.z = z

 def print_3D(self):
  print "(",self.x,",",self.y,",",self.z,")"

## just test the our classes ##

p2 = Point2D(1,2)
p2.print_2D()
print p2.product(Point2D(2,1))

p3 = Point3D(5,4,3)
p3.print_2D()
p3.print_3D() # inherited method
print p3.name # inherited attribute
print dir(Point2D)
print dir(Point3D) # dir return a list with attribute and methods of the class
( 1 , 2 )
4
( 5 , 4 )
( 5 , 4 , 3 )
A dummy name
['__doc__', '__init__', '__module__', 'name', 'print_2D', 'product']
['__doc__', '__init__', '__module__', 'name', 'print_2D', 'print_3D', 'product']