Showing posts with label methods. Show all posts
Showing posts with label methods. Show all posts

Tuesday, September 15, 2009

Python - create static methods in a class

#create static methods in a python class

import math

class MyStaticClass:
def getSqrt(num):
return math.sqrt(num)
def getHalf(num):
return num/2
# labels the methods as static
getSqrt = staticmethod(getSqrt)
getHalf = staticmethod(getHalf)

MyStaticClass.getSqrt(144)
12.0
MyStaticClass.getHalf(20)
10

Tuesday, July 7, 2009

The Python list and methods of the python list

# basic list usage and list methods 
 
# a list is created with the "[]" square brackets 
l = []
 
# add a single item into a list 
l.append("apple")
print l
#output: 
# apple 
 
# remove the last item appended 
l.pop()
#output: 
# apple 
 
print len(l)
#output: 
# 0 
 
# create and then iterate through a list 
l.append("apple")
l.append("pear")
l.append("peach")
l.append("apricot")
l.append("banana")
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
for fruit in l:
    print fruit
 
#output 
#    apple 
#    pear 
#    peach 
#    apricot 
#    banana 
 
# find the index of items in a list 
l.index("apricot")
#output: 3 
l.index("apple")
#output: 0 
 
# remove specific items from a list 
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
l.remove("peach")
print l
#output: 
# ['apple', 'pear', 'apricot', 'banana'] 
 
 
# More on lists:  http://docs.python.org/tutorial/datastructures.html