Wednesday, January 22, 2014

Reflecting on Object Oriented Programming

    In class we have been working on object oriented programming. I remember when we started this at the end of csc108, I was confused by it (especially with why some methods had underscores surrounding them, what does it mean??) but now I feel I have a good grasp on the technique, and understand the purpose of the __init__ method (among others). Something that does still bother me that I noticed while doing last weeks Exercise is that, if you have a method, 'hop', within class 'Bunny', and you let a = Bunny(), and you call a.hop(), everything is fine. But, if you say something like, a.hop = 'hop', and then try to call a.hop() again, you get an error! It seems like this is because python now associates a.hop with the string 'hop', so when you call a.hop() again, it is substituting 'hop' in, so it thinks you're trying to call a string as a function. However, if you call Bunny.hop(a), it will still work. So, I guess I understand (vaguely) why this happens, but I still find it a bit irritating and inconsistent.
    Also, I don't understand the benefit of writing our function definitions as something like, "def hop(self: 'Bunny') -> None", especially since python red-underlines the "-> None" part. Why are we writing it like this? Me and python agree that it is silly, though I can see how it would be useful if you want to give a variable in the function a set value (such as "def hop(self: 'Bunny', jump = 'yes') ... print(jump) " would print 'yes' if a.hop() was called, or you could say a.hop('no') and it would print 'no'). Anyway, those are my thoughts for the week, so long!

1 comment:

  1. I googled it, and the reason for the "def hop(self: 'Bunny') -> None" thing is just for sake of having a standard convention for representing the types of the parameters and return value. Otherwise we have a bunch of different ways of representing the information (like the one we are familiar with from 108), and the lack of a standard serves only to confuse programmers.

    With respect to why we might prefer this style to the one from 108, I think this perhaps provides more information at a glance. When I look at the function header, I can see a name associated with a type (and perhaps associated with a default value), whereas, otherwise, I would have to look back and forth between two lines, and try to match names with their corresponding types.


    Also, I love the slug. Should deck the dude out with a laptop.

    ReplyDelete