Why do some methods use dot notation and others don't?

methods, python, syntax

Solution

The key word here is method. There is a slight difference between a function and a method.

Method

Is a function that is defined in the class of the given object. For example:

class Dog:
    def bark(self):
        print 'Woof woof!'

rufus = Dog()
rufus.bark() # called from the object

Function

A function is a globally defined procedure:

def bark():
    print 'Woof woof!'

As for your question regarding the `len` function, the globally defined function calls the object's `__len__` special method. So in this scenario, it is an issue of readability.

Otherwise, methods are better when they apply only to certain objects. Functions are better when they apply to multiple objects. For example, how can you uppercase a number? You wouldn't define that as a function, you'd define it as only a method only in the string class.

Problem

So, I'm just beginning to learn Python (using Codecademy), and I'm a bit confused. Why are there some methods that take an argument, and others use the dot notation? len() takes an arugment, but won't work with the dot notation: ``` >>> len("Help") 4 >>>"help".len() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'len' ``` And likewise: ``` >>>"help".upper() 'HELP' >>>upper("help") Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'upper' is not defined ```

Original source