OOP concept in Python - Part 2


Methods 

One way we can improve our use of classes is to add functions to them. These class functions are known by their more common name, methods. In Python, methods are defined as part of the class definition, but can be invoked only on an instance. In other words, the path one must take to finally be able to call a method goes like this:

(1) define the class (and the methods),
(2) create an instance, and finally,
(3) invoke the method on that instance. 

Here is an example class with a method

class MyDataWithMethod(object):             # define the class
 def printFoo(self):                                    # define the method
 print 'You invoked printFoo()!'

You will notice the self argument, which must be present in all method declarations. That argument, representing the instance object, is passed to the method implicitly by the interpreter when you invoke a method on an instance, so you, yourself, do not have to worry about passing anything in (specifically self, which is automatically passed in for you).

For example, if you have a method that takes two arguments, all of your calls should only pass in the second argument. Python passes in self for you as the first. If you make a mistake, do not worry about it. When an error occurs, Python will tell you that you have passed in the wrong number of arguments. You may make this mistake only once anyway... you'll certainly remember each time after that!

Now we will instantiate the class and invoke the method once we have an instance:

>>> myObj = MyDataWithMethod()                 # create the instance 
 >>> myObj.printFoo()                                      # now invoke the method 
 You invoked printFoo()

We conclude this introductory section by giving you a slightly more complex example of what you can do with classes (and instances) and also introducing you to the special method __init__() as well as subclassing and inheritance.

Thank you :)

Comments

Post a Comment

Popular posts from this blog

Python Matrix

Angular : List of Topics

What are the steps involved in the concreting Process?