Main Content

Python - function v method

Archive - Originally posted on "The Horse's Mouth" - 2006-10-20 17:42:13 - Graham Ellis

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