On Mon, Aug 22, 2011 at 3:11 PM, Prasad, Ramit <[email protected]>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
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor