Ever wonder what puts a programming language in motion? How does it all work? How does the language interpreter know what the simple signs +, -, * mean? In a programming language — in each and every one — we must be able to express some of the most basic actions, such as adding (numbers) or appending sets with new elements.
Let's unveil the secret: in programming, the implementation of basic activities takes place through the use of methods.
To go to Polish language version click here
A few words about the methods
In the previous passage, we discussed ordered collections, called sequences. Yes, we know. You would probably like to practice sequence operations. See how it all works. We promise to take care of it quickly. But before we move on to the exercises, we still need to devote some energy and time to theoretical issues. You just can't skip some things.
What exactly do we mean? Methods! Methods are the salt of a programming language.
Methods are basic instructions for a computer to execute simple, single operations
Python has a whole set of pre-defined methods from which you can choose the most — at the moment — interesting ones and use them to your satisfaction. A bit like a carpenter-artist who has whole sets of various blades, drills, discs and cutters suspended above the table — and in a given situation, he reaches for the right one. Believe us: methods can really make your job easier.
The difference between a function and a method
Where did the name "method" come from? A method, as we have just said, is an "operation", an "action". But hold on a second: we know from the literature for novice programmer's that we usually call these separate actions functions[1]. So where does the new name come from: method?
The term "method" is taken from the object-oriented paradigm. Modern programming languages are — most often — object-oriented languages. In this series of articles, we will come to — in due course — what object-oriented programming is and try to explain it thoroughly. In our opinion — considering the available resources of books, courses and tutorials related to programming — describing the very essence of object-oriented programming is one of the more neglected topics. Despite the vastness of the literature, the essence of the issue somehow eludes. Promise to return to it soon. Unfortunately, not all at once. For now, let's get back to the interrupted thread.
So, what's the difference between a function and a method? The ready-to-use built-in function is simply a wider concept. Functions — in a broad sense – may be divided into, let's call it, "ordinary" functions and methods, which are also functions, only a bit specific.
The uniqueness of methods consists in a fact that they are assigned to a specific data type (objects).
Don't be afraid of the word "object"; if it irritates you, at this stage of learning you can say "data" instead of "objects". In the programming language, objects (data) are grouped into object types (data types); examples of data types are: string, int, list, dictionary.
While built-in functions can be applied to different types of data, methods are assigned to one specific data type. Due to the fact that methods are assigned to a certain type of objects, the object becomes something superior to the method, the object "has" methods. Hence, calling the method requires the name of the object and — after the dot — the name of the method (the so-called dot notation):
object.method()
Methods are the tools by which a mutable object changes its state[2].
Comparison to the real world
We often look for analogies between the virtual (programming) world and the real (physical) world that surrounds us. The question is whether there are also objects in the real world with methods that change the state of these objects?
Answer: It would be difficult to find such an object, and if so, probably in futuristic movies like "Transformers", where (on request) the object changes shape, color, size.
In the vast majority of cases, objects do not have the ability to change themselves. Let's take clothing as an example. When you want a jacket in a different size — than the one you currently have — you have to buy a new one. It is impossible to enlarge an existing jacket. Likewise, the color of the jacket is predetermined once and you won't make a green jacket pink. By the way, wouldn't it be nice to have a jacket at home that changes color at the click of a finger? Every day a jacket in a different color? Sounds good, but for now remains in the sphere of dreams …
A super jacket that changes color — it is the logical equivalent of mutable programming objects. Such objects are, for example, lists.
Regular jacket — this is the logical equivalent of immutable objects such as a string. If you run a certain method on a string object, you expect that object to change, e.g. by transforming lowercase to uppercase ('house' → 'HOUSE'). However, running such a method actually causes Python to create a new 'HOUSE' object on top of the existing 'house' object.
How to learn methods
Learning a programming language is a bit like learning a foreign (human) language. You don't know the words — you have no chance of using the language freely. Similarly, in computer languages — knowledge of the syntax is necessary (computer language requires more precision than human language; therefore, in computer languages we place more emphasis on syntax than on the vocabulary itself).
The lion's share of language syntax consists of ready-made functions and methods. So it's worth mastering them.
Of course, this does not require learning the syntax of the methods by heart. Just have a chart with the methods for the given data type at hand. It is relatively easy to find method lists on the internet for a specific type of Python object.
For example, you can use the w3schools portal. Enter the following address in the browser window: https://www.w3schools.com/python/python_ref_string.asp
On the left side of the screen you will find a menu from which you can choose an overview of:
- built-in Python functions (i.e. tools applicable to various data types)
- methods for string data-type
- methods for list type data-type
- methods for dictionary data-type
Take a look at the screenshot:
After clicking, the method chart appears:
Of course, the starting point is to know what task you have to do — then to choose the appropriate method. Let's say you want to count how many times a certain phrase appears in a string, e.g. 'sport' in the string: 'I do sports, sport is very important in our lives. It improves our well-being. We feel bad without sport.'
The description of the methods shows – that the count() method is used to estimate the number of phrase appearance in the string. So, let's select it from the list to see its syntax:
string.count(value)
For simplicity, we have omitted the optional parameters. (W3schools also illustrates the syntax with a short example to make it easier to illustrate the application of the method).
Now there is nothing more to do as just use the chosen method:
string = 'I do sports, sport is very important in our lives. It improves our well-being. We feel bad without sport.'
x = string.count('sport')
print(x)
Output: 3
The count() method has calculated the number of occurrences of the word 'sport' in the given string and returned the result. The word appears three times.
Of course, let's not be naive. There will not always be a method that perfectly solves the problem we have to face. It will also happen that the appropriate method does exist, but somehow we did not figure out that this is the one that would be useful to us. In short, the table with noted methods is not a substitute for practice, exercises, browsing the code, thinking, trying, looking for solutions.
Summary
Python comes with sets of ready-to-use tools for performing simple, "unit" tasks; these tools are pre-defined functions and methods.
Functions are usually used in "wider areas" than methods that are dedicated only to a specific type of data.
The way of invoking a function: function(object) is different than the way of invoking a method: object.method().
Appendix: Methods with two underscores
Beginning programmers tend to consider mathematical operators as the most elementary expression of actions carried out in a programming language. Nothing could be more wrong. Currently, high-level languages – under the hood – replace mathematical operators with (logically corresponding) methods. The methods, then, are the most basic way of expressing actions.
For example, in Python, the "+" operator is replaced with the __add__ method. The expression x+1 is therefore equivalent to the expression x.__add__(1).
Of course, overloading takes place in the background, in a way that is imperceptible to the user. While perhaps the computer prefers a slightly weird looking method with two underscores at the beginning and end, you (as a human) will definitely prefer the plain '+' sign.
As taught on math lessons in primary school…
[1] A function is a statement (or block of statements), which is used to perform a specific task.
[2] there are also immutable objects in programming, which will be discussed in a moment