Method is one of the most important thing exist in python programming language. Understanding about how to create a method is very important in python programming language. To put it simple, method is actually a function. But in case of the method, an object is actually own it. So, what is actually an object ? Everything in python is an object. For an example if there is a variable with the type of string, list or numeric and any other types, all of those are objects, and every object has a function where only that object can use it.
For an example, every string object has a lowercase method where this lowercase method cannot be used by any other objects such as list. But list also has another function such as index, where this index function itself cannot be used with any objects with another type such as string for an example. So the main point is that the function which is owned by an object is called a method.
Executing Built-in Method of an Object
The following is an example of using a method in python programming language. The first context is the usage of a built-in method as follows :
Microsoft Windows [Version 10.0.18362.1016] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\Personal>python Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> capital_letter = 'THIS IS A STRING WITH CAPITAL LETTER'; >>> print(capital_letter) THIS IS A STRING WITH CAPITAL LETTER >>> print(capital_letter.lower()) this is a string with capital letter >>>
The above output of the command execution is execution of a method with the name of ‘lower()’. This method is available only for string object. The string object in the above example is ‘capital_letter’.
>>> job_vacancy = ['CEO','HR Head Dept','Finance Head Dept'] >>> print(job_vacancy.index('CEO')) 0 >>>
The execution on the above output has a different command execution. It is the execution of a method with the name of ‘index()’. This method also need an additional string parameter as in the above output. So, it has a different form compared to the previous method where it doesn’t need any additional parameter. This method is available only for list object. The list object in the above example is ‘job_vacancy’.
On the other hand, if there is an execution of an incorrect method from each object, it will generate an error as follows :
>>> print(capital_letter.index('THIS IS A STRING WITH CAPITAL LETTER'); File "<stdin>", line 1 print(capital_letter.index('THIS IS A STRING WITH CAPITAL LETTER'); ^ SyntaxError: invalid syntax >>> print(job_vacancy.lower()); Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'lower' >>>