Sunday, 26 January 2014

Week 3 OOP

One of the main topics in the our first 3 weeks of CSC148 is the benefit of using object-oriented programming (OOP), which involve writing classes, in creating code and projects. Using classes saves the programmer from rewriting similar code and provides clear organization of both readability and usability. At face-value, they serve the same function as user-defined functions; that is, you write a collection functions to avoid rewriting written code. The design of this style, however, with object-creation, object attributes, and inheritance, can provide structure that linear programming does not provide. Each class is analogous to a factory that can spit out an object with specifications you make and an instruction manual on what it can do (dir()). The use of inheritance provides an organization of objects often similar to our own organization of things in day-to-day life: using a branching tree that starts out broadly and branch into more and more specific levels. For any large-scale programming projects you may work on, OOP is of tremendous importance.

For a review or intro-level overview of programming with OOP, MIT ocw is a good source. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/video-lectures/ They even have assignments and lecture slides and transcripts posted.

Python has a free-for-all mentality, and both programmers and users can define and change almost anything they want about an object, such as its attribute value. Sometimes when writing OOP code for some audience, you may want to hide away the user's ability to change an object's attribute. One way of doing this is using "property" inside your class definition. When the user types "my_object.attribute_1" or "my_object.attribute_1 = new_value", it looks like they are accessing attribute variables, when really, they are accessing a get_attribute function and a set_attribute function. This allows you to control what happens when the user accesses and set an attribute (including raising an error), without requiring the user to type pesky method calls like "my_object.set_attribute_1(new_value)".

Raymond Hettinger, one of the developers at Python, had a talk about basic Pythonic ways of creating and using a class, including topics on variable privacy and property discussed above. http://pyvideo.org/video/1779/pythons-class-development-toolkit