We already have seen many examples of methods while learning objects and data structures types in python. So let’s make our method knowledge more robust.
Methods are functions built into objects. They are always called with an object.
Later on, we will learn how to create our own objects and methods using Object Oriented Programming (OOP) and classes.
Methods perform a specific action on an object and can accept arguments just like a function in python.
General Syntax of a method is:
Here arguments can be self-referring to the object itself.
let’s take some examples of various methods which list has in python.
# Create a simple list p = [2, 6, 4, 8]
The methods for a list are:
Let’s see what they actually do?
#using remove() in list p.remove(6) print(p)
[2, 4, 8]
#using append(adding element) p.append(7) print(p)
[2, 4, 8, 7]
#using sort(arrange in order) p.sort() print(p)
[2, 4, 7, 8]
#using count(),lets count how many times 4 comes. print(p.count(4))
After reading this post, you should feel comfortable in calling methods through objects in Python.