[Tutor] methods vs. functions

Wayne Werner waynejwerner at gmail.com
Mon Aug 22 23:49:01 CEST 2011


On Mon, Aug 22, 2011 at 3:11 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote:

> Steven D'Aprano wrote:
> >(Methods are very similar to functions. At the most basic level, we can
> >pretend that a method is just a function that comes stuck to something
> >else. Don't worry about methods for now.)
>
> Can someone please explain the difference between methods and functions?
>
> Thanks,
> Ramit
>

You could define a function as a reusable section of related code.
Technically speaking, it doesn't have to be related, but that's bad
programming.

A method is a section of related code that is attached to related data.

For instance, say you have a string that you would like to reverse. How
would you do it, if Python didn't have batteries included?

Here's the functional way:

def string_reverse(string):
    return_string = ""
    for x in xrange(len(string)-1, -1, -1): # range in Python 3.x
        return_string += string[x]
    return return_string

mystring = "Norwegian Blue"
print(string_reverse(mystring))

However, if you wanted to view strings as objects - "things" if you will,
you can create a class:

class String:
    def __init__(self, startvalue=""):
        self.value = startvalue

    def reverse(self):
        self.value = self.value[::-1] # Using slicing

mystring = String("A Slug")
mystring.reverse()
print(mystring.value)


HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110822/11862ba7/attachment-0001.html>


More information about the Tutor mailing list