Deciding between a function or a method for standard operators


#1

I had a generic question regarding functions vs methods. I understand the theoretical difference between them. But how is it decided whether an operator should be written as a function or a method? For instance, why is len("somestring") defined as a function while "somestring".lower() is defined as a method?

Thanks.


#2

you are calling len(whatever) in which len is an already written function.
thus is the reason len is a function, not a method..

.whatever is not a function, because you are calling it on something else, instead of by itself like len..


#3

A function acts on an argument passed in to it. It is in global scope, usually (if it is a built-in, such as len()). A method acts on an argument in the context of an owner object defined by a class. "something" is defined by the String class, so has string methods (methods defined in the class) at its disposal. The argument may be internal, as in a property of the class instance, such as, self.property.

def my_function(param):
    # do something with `param`

The above is a function.

class MyClass:
    def __init__(self, prop1, prop2):
        self.prop1 = prop1
        self.prop2 = prop2

    def say_prop1():
        print self.prop1

    def say_prop2():
        print self.prop2

In the above, say_prop1 and say_prop2 are methods accessible to instances of the class.


#4

That explains things perfectly. Thank you.