« Python - extend v append on a list | Main | Python - listing out the contents of all variables »

October 20, 2006

Python - function v method

What's the difference between a function and a method? A function is a named piece of code that performs an operation, and a method is a function with an extra parameter which is the object that it's to run on.

Example:

class hotel:
 def __init__(self,name,nightly):
  self.name = name
  self.nightly = nightly
 def getweekly(self):
  return 7 * self.nightly

def seventimes(amount):
 return 7 * amount

# -------------------------------

manor = hotel("Well House Manor",90)
beechfield = hotel("Beechfield",120)

# Calling a METHOD - a function on an object

ma_am = manor.getweekly()
be_am = beechfield.getweekly()

# calling a FUNCTION - less useful code as it
# does not give an implicit link to the data
# that it's on.

rz = seventimes(240)

print ma_am, be_am, rz

Posted by gje at October 20, 2006 05:42 PM

Comments

My house is my castle. Anthony.

Posted by: Anthony at October 27, 2006 08:09 PM

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008