Search code examples
pythonbuilt-in

Differentiating between built-in functions vs built-in methods in Python


I have had some struggles understanding Python's built-in functions and methods. From what I understand, functions return information about something whereas methods change something. Is this correct?

Also not clear to me is why some functions and methods require parameters while others do not. Is this requiring-parameter quality specific to either functions or methods?

Finally, why do some of these built-in functions/parameters simply state their name followed by parameters (eg sorted(list)) while others (eg list.sort()) use a period in their syntax?


Solution

  • A method is a function which is applicable to a certain class, while a function can be used in any valid class. Like the sort method for the list class sorts the list. Methods of mutable types mostly change the item, so list.sort would set the value of list to the sorted value of list and return None. But methods of immutable types like strings will return a new instance of the thing as seen below.

    question = "How is this?"
    question.replace("How", "What")        # Returns "What is this", but does not change question.
    print(question)                        # Prints "How is this?"
    print(question.replace("How", "What")) # Prints "What is this"
    

    Built in functions like sorted do not change the item, they return a new version, or instance, of it.

    list1 = [4,3,6,2]
    sorted(list1)    # Returns [2,3,4,6], but does not modify list.
    print(list1)     # Prints [4,3,6,2]
    list1.sort()     # Returns None, but changes list.
    print(list1)     # Prints [2,3,4,6]
    

    When you use a method, you put a period after the variable to show that it can only be used for that specific class. Why some functions require arguments while some methods don't - like sorted(list) requires list, but list.sort() doesn't require arguments, is that when you use a method on a class, Python by default passes in a parameter called self, which is the actual variable, list in this case. If you have worked with JavaScript, self is something like the this keyword in JS.

    So when you enter list.sort(), Python is actually running the function sort inside the list class passing it a parameter of self.