Methods

The distinction between methods and functions is somewhat sublte. They are functions that are built into objects, and are a subclass of functions. Functions are "general purpose" and do not belong to objects. We've talked about list, tuple, string, and dictionary methods. Even numbers themselves have methods. Any call to a function that belongs to an object is called a method. The format is the following:

object.method(arg1, arg2..)

We can observe that there is an object here.

Let's create a list object and try out some built-in methods (we can even create our own methods, coming in the next chapter).


In [ ]:

Number Methods


In [33]:
# Numbers have methods, too
my_num = 2
print(my_num.__add__(3))
print(my_num.__sub__(2))
print(my_num.__mul__(2))
print(my_num.__truediv__(2))


5
0
4
1.0

List Methods (Recap)


In [37]:
# These are examples of list methods.
my_list = ["Bonet", "Triggly", "Ross"]

my_list.append("Triggly")
print("After appending {}".format(my_list))
another_list = my_list.copy()
print("After copying {}".format(another_list))
my_list.clear()
print("After clearing {}".format(my_list))
another_list.insert(2, "Triggly")
print("After insertion: {}".format(another_list))
the_count = another_list.count("Triggly")
print("Count of specific word: {}".format(the_count))


After appending ['Bonet', 'Triggly', 'Ross', 'Triggly']
After copying ['Bonet', 'Triggly', 'Ross', 'Triggly']
After clearing []
After insertion: ['Bonet', 'Triggly', 'Triggly', 'Ross', 'Triggly']
Count of specific word: 3

Tuple Methods (Recap)


In [38]:
# These are some tuple methods
my_tuple = ("hate", 19.0, "redemption", "hate")

print(my_tuple.count("hate"))
print(my_tuple.index("redemption"))


2
2

Dictionary Methods (Recap)


In [39]:
# These are Dictionary Methods
my_dict = {"Sally":19, "Robert":[1, 48, 29], "Wallace":0}

keys = list(my_dict.keys())
values = list(my_dict.values())
popped_value = my_dict.pop("Robert")
print(popped_key)


[1, 48, 29]