Sunday, February 25, 2018

Methods


Methods in Python have both similarities and differences to Java and other languages. Now that we have explored the concepts of loops and conditionals and are aware of some Python syntax, structure, and indentation rules, looking at the nature of methods is a good next step!

Basic Structure

  • First off, in Python, a class is necessary to run a method, so we must create one followed by a colon. 
  • Then, after an indentation, you need to define your method using the word 'def' followed by the name of the method. After the name of the method, in parentheses, we need to type the word 'self.' By convention, this is always the first argument in a method, so whether we have arguments to pass in or not, we need 'self' to refer to the newly created object. As in other Python code structures like loops and conditionals, we end this line with a colon. 
  • Following another indentation on the next line, we code what we want the method to accomplish. In the following example, I simply have a print statement, but methods can have multiple lines and statements in this section as long as they adhere to Python indentation rules.
  • Finally, to call the method, we call the method within the class. The example below is a very basic picture of what a Python method looks like: 




Constructor and Instance Variables

Now that we know the basics, let's define instance variables inside methods. The  __init__ constructor method is called once for any object of a class. In this example, we add numbers by passing parameters into the constructor. We define the instance variable sum within the method and then outside of the method, we print it. 



Note that alternatively, we would get the same result as the above program without using an instance variable, but my goal with the above example was to show how instance variables can be incorporated into methods:


We can also get the same result by calling our own created method instead of the constructor. When we write a method without a constructor, Python executes a default constructor that doesn't do anything. The difference between the code below and the code right above is that we have to create an object (adding) of the Addition class. The following method follows the same formula as the Basic Structure example.



Main Method

As in other object-oriented programming languages, we can use a main method to call all of our other methods. This is the sort of structure we would want to use as our programs become more complex and developed. The example below shows some key features of the main method:
  • Notice first that the final line of code calls to execute the main method. Without this, nothing happens.
  • In the Dog class, we declare class variables, define a constructor method, and define another method called set_score.
  • In the main method we create objects and pass in variables to run the constructor method to set up that object's instance variables.
  • We can print instance variables as well as class variables for a particular object from the main method.
  • We can call the method set_score in the Dog class from the main() method.




Lessons

There are different ways to do things to do things in Python. For example, instead of simply writing "main()" at the end of my program, I could have written a longer statement: 

if __name__=="__main__": main()

This is what my source was directing me to do. At first I did not understand it, so I looked up the purpose of this lengthy and confusing statement. In Python, __name__ is set to __main__ whenever a file is being executed, so when you run your program, if __name__=="__main__" returns true, which executes main(). But I found that if I eliminate the conditional my program still works. I am sure there are cases when the conditional is necessary, but in my case it was not. The lesson learned was that not everything is as complicated as sources might tell you, so it's worth monkeying around on your own to find what might be a simpler and more understandable version of your code.

Also, when I was putting this together, I was getting quite a few errors for various little things here and there. I think most of them were related to a struggle to remember how object oriented programming works, so if you've been away from this type of programming, I hope this post was a nice refresher!



Sources:

https://stackoverflow.com/questions/3786881/what-is-a-method-in-python
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://stackoverflow.com/questions/22492162/understanding-the-main-method-of-python

2 comments:

  1. Could you elaborate more on bound and unbound methods in Python? Does all instance method require an object to reference them?

    ReplyDelete
    Replies
    1. Python 3 eliminated unbound methods, so all methods in the most recent version of Python are bound. Until a method is bound, it is simply a function. As for your second question, I found a way to execute a method without creating an instance of the class:

      class Addition:
      def add_nums(self,a,b):
      print(a+b)

      Addition().add_nums(2,3)

      I hope this answers your questions!

      http://blindvic.blogspot.com/2012/01/explaining-bound-and-unbound-methods-in.html

      Delete