Monday, December 25, 2017

Python Methods

Among other Python types, we've created strings, floats and lists, like the ones you see here. Each one of these values or data structures is so-called Python object. This string is an object, this float is an object, but this list is also an object.

These objects have a specific type that you already know: string, float, and list, 
But next to that, Python objects also come with a bunch of so-called "methods". You can think of methods as _functions_ that "belong to" Python objects. 

A Python object of type string has methods, such as capitalize and replace, but also objects of type float and list have specific methods depending on the type.

Suppose you want to get the index of the string "mom" in the `fam` list. `fam` is an Python object with the type `list`, and has a method named `index()`. To call the method, you use the dot notation, like this. The only input is the string "mom", the element you want to get the index for. Python returns 4
You can call the method `capitalize()` on `sister`, without any inputs. It returns a string where the first letter is capitalized now:
In Python, everything is an object, and each object has specific methods associated. Depending on the type of the object, list, string, float, whatever, the available methods are different.

A string object like `sister` has a replace method, but a list like `fam` doesn't have this, as you can see from this error.
Some methods can change the objects they are called on. Let's retake the `fam` list, and call the `append()` method on it. As the input, we pass a string we want to add to the list:

Python doesn't generate an output, but if we check the `fam` list again, we see that it has been extended with the string `"me"`:
You have Python functions, like type(), max() and round(), that you can call like this:

There are also methods, which are functions that are specific to Python objects. Depending on the type of the Python object you're dealing with, you'll be able to use different methods and they behave differently.

You can call methods on the objects with the dot notation, like this for example.


Post a Comment


Talk to us (+91-9738925800)