Wednesday, 25 February 2015

Object-Oriented Programming







Up until now we have been learning the basics of object - oriented programming in Python. We have learnt how to create our own objects by creating classes with certain attributes and how to give the objects their own functions known as “methods”. While you can create your own methods that can do anything a function can do, we have learnt about the special python methods. These methods allow you to do things within python like check if two objects are equivalent (with the __eq__ method) and create a string representation of the object when you print it or use the str() function. These special methods are identified by being surrounded by double underscores e.g., __str__. One thing that I always wondered while using Python was if there was a way to make objects and attributes private as you can in most other programming languages, and I found out you cannot but we did learn a way to mimic privacy. This is done using Python’s built-in property() which basically allows you to control what happens when you try to change and access an attribute of an object. In class we used property() to only allow a variable to be set by the user once by controlling what happens when you try to change the value of a variable. We learnt that if you want an attribute to be untouched you up a “_” before the name, this does not actually make it private but it tells the user that it is at their own risk to change it.


The most interesting and useful thing we have learnt in OOP so far was how to make objects inherit attributes and methods from other objects. This was the main focus of assignment 1 and I think it was very helpful for it to be so. Understanding how to make a base class that covers all of the base needs many other classes will need is very helpful as it saves coding time and helps prevent errors from copy-pasting code.

No comments:

Post a Comment