Why in Python are there functions where the parameter should be placed between parentheses and others should be placed with a dot and the function name?

Asked

Viewed 103 times

0

There are functions that should be written as for example

sorted(variavel)

and others are written as

variavel.sort()

I know the differences between the two functions above, I just used to exemplify. I just want to understand the difference in the way of writing functions in Python.

1 answer

1


The first syntax is considered more imperative, that is, the function is what matters most, so it comes first, and the object that will be manipulated within it is only one argument of function.

The second syntax is considered more object-oriented, so what matters most is the object that will be manipulated, so it comes first. And from this object you call a function that will execute something with it. This function passes to call method because it is linked to an object.

The second makes the function a member of a structure as well as accessing a data type field.

In practice it is the same, when executing the second it calls equal to the first, it is only a way to show that the object is important, but the function will be called and the argument passed to it will be the object that came before it.

It has a readability advantage for some scenarios and an IDE can help by showing the methods it can call from that object which helps a little. The IDE needs to be much smarter in Python because it is a dynamic typing language and the type of the variable can change, so it becomes a bit complicated to "guess" what type is at that point in the code. In some cases impossible to know which object is that and help is not possible.

When you have a function that works for many different types it can be more interesting the first syntax. When the method is only for that guy the second might be better.

In Python the second is only possible if the method was defined within a class of that type (unless you have some syntax exception from the language for things builtin).

  • Remember that in the specific example of the question, sorted returns another list, while lista.sort() modifies the list in place

  • @hkotsubo yes, I didn’t get into that point because he said he knows these differences and only used it as an example to ask about the syntax. This question is punctual.

  • exactly, the difference between the two I know. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.