Sunday, March 11, 2012

Introduction to Methods

In this post I am going to discuss how Methods work in Python.

What are Methods?
In simple words, methods are something that can be done to an object. By something I meant anything that can be done to an object like delete, append, count, etc.

Lets take help of an example. Lets say "Driving a Car Fast"

Here driving would be a method(Action), Car would be an Object, and Fast would be an argument.

So we would write it in this way.
car.driving(fast)

So the syntax is : objectname.action(argument)

Now lets check with few examples in IDLE, lets create a List.

>>> py1 = [12,45,78,90]
>>>

append is a built in function, and this adds elements to the end of a List

>>> py1 = [12,45,78,90]
>>> py1.append(50)
>>> py1
[12, 45, 78, 90, 50]
>>>

So we see here that 50 is added to the end of the List

Lets see one more example.

count is a function, which basically counts the number of time an element is present in a List.

We will create another List.

>>> python = list("I am Whiskey, and I Like to Program in Python")
>>> python
['I', ' ', 'a', 'm', ' ', 'W', 'h', 'i', 's', 'k', 'e', 'y', ',', ' ', 'a', 'n', 'd', ' ', 'I', ' ', 'L', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', ' ', 'i', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
>>> python.count('i')
3
>>> python.count('a')
3
>>> python.count('w')
0
>>> python.count('W')
1
>>> python.count('x')
0
>>>

Okay we see here that count, check how many times an element appears in a List. Also note that its case - Sensitive, check in case of W, lower case w, was not there in the List hence is returned 0, but upper case W appeared once, hence it returned 1.

Lets check one more example.

extend is a function, which is almost similar to append.

Lets Make Two List.

>>> list1 = [10,20,30]
>>> list1
[10, 20, 30]
>>> list2 = [40,50,60]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50, 60]
>>> list1 = [10,20,30]
>>> list2 = [40,50,60]
>>> list2.extend(list1)
>>> list1
[10, 20, 30]
>>> list2
[40, 50, 60, 10, 20, 30]
>>>

So we see here that extend function, appends another list to a list.

I hope this was informative for you, and now we know the basics of Method and how it works.

Task: Make 4 Lists and practice with the functions given in this post.

Thank You and Don't forget to check my next post.


0 comments:

Post a Comment