Sunday, February 15, 2015

OOP

    At first I thought we are supposed to write about OOP after the reading eek, cause it didn't look like something we have already covered. Then I realized it is due before reading week. Looked it up and found out this is pretty much what we were doing throughout this whole course.
    Will start with Class first, because it's kind of hard to explain other concepts without it. Class allows us to create an object with certain set  of attributes, which are of the same(or very simmilar) types for all objects of one class.
    Inheritance lets us create subclasses (which are based on bigger classes called superclasses). They are needed in order to make code more flexible and easier to edit in the future without applying the same changes again and again for every little class we need. Instead we can just change superclass, and all the generic attributes inherited from it by subclasses will be changed as well. For example creating a superclass Shape which has one attribute which all shapes are going to use, regardless of what the actual shapes are, their sizes, colors etc. That is position. And then create subclasses of shape for example Square or Triangle which will have different amount of sides, hence won't be able to inherit this attribute from parent class.
    Methods do the same thing as functions do, except for they are attached to classes while functions are written in the module. We can use methods to create and change(aka mutate) characteristics of an object. If we take class Square from previous example, we would might want to write a method change_base which would change the length of base of square already created. There are 4 methods which have to be included in most classes: __init__,  __str__,  __repr__,  __eq__.
   __init__ allows you to create an instance of an object
    __str__ gives a string representation of an object description understandable for user
    __repr__ provides information on an instance of a class which is precise enough to create an exact copy of an object
    __eq__  lets us check if two objects are the same, based on attributes we want to check rather than just checking where the object is stored in memory.

No comments:

Post a Comment