Thursday, February 26, 2015

Object-oriented programming (OOP)







Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.Object Oriented Programming involves the creation of objects which contain both data and functionality together. It involves defining your own class and creating attributes (properties created for the object) and methods, which are operations that can be performed for an object. Everything in Python is an object. The user defined objects are created using the class keyword. From classes we construct instances. An instance is a specific object created from a particular class. Consider this pieces of code (retrieved from the CSC148 course website):

from math import sqrt

class Point:
    """
    A n-dimensional point.
    coords is a list of numbers containing the coordinates
    of this Point.
    """

Attributes

Attributes are characteristics of an object. A special method called __init__() is used to initialize the attributes of an object.

def __init__(self, coords):
        """
        (Point, list of number) -> NoneType
        
        Initialize this point with these coords.
        We will return to this docstring to add an example
        showing that p is as it should be.
        
        >>> p = Point([3, 4.0, 5.32, 6, 7])
        >>> p.coords
        [3, 4.0, 5.32, 6, 7]
        """
    
        self.coords = coords
    
In this code example, we have a Point class. The special method __init__() is called automatically right after the object has been created.

Here we pass an attribute to an instance object.

p = Point([3, 4.0, 5.32, 6, 7])



Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. For example, we might have a distance_from_origin() method in our Point class. The distance_from_origin() method returns the the distance from the particular Point to the origin.

def distance_from_origin(self):
        """
        (Point) -> float
    
        Return the distance from this Point to the
        origin.
        
        >>> p = Point([3, 4])
        >>> p.distance_from_origin()
        5.0
        """
        
        sum_of_squares = 0
        for coord in self.coords:
            sum_of_squares += coord**2
        return sqrt(sum_of_squares)



Special Methods

Classes can implement certain operations with special method names. 
In our code example, we have a Point class. Here we introduce four special methods. The __init__(), __str__(), __eq__(), and  __repr()__ methods.

 def __str__(self):
        
        return str(tuple(self.coords))
    
    def __repr__(self):

          return "Point({})".format(self.coord)        
    def __eq__(self, other):
          
         return ( # parenthesis for grouping across lines
            isinstance(other, Point) and # make sure other's a Point and
            self.coord == other.coord # check whether coords are equivalent
            )



Inheritance
    Another concept of object oriented programming is inheritance. Inheritance is when you create a general class (usually called the parent class) and then create sub-classes (usually called child classes) that use (inherit) methods and attributes from the parent class. When you intend to make your code more flexible and efficient, it's good way to use inheritance. Since you can use common methods and attributes in the general class for many sub-classes instead of re-writing the same code in every sub-class. Here is some code the an example of inheritance.

class A:
   def g(self, n):
      return n
      
   def f(self, n):
      return self.g(n)
      
class B(A):
   def g(self, n):
      return 2 * n

a = A()
b = B()
print("a.f(1): {}".format(a.f(6)))
print("b.f(1): {}".format(b.f(6)))

>>> 
a.f(1): 6
b.f(1): 12
>>> 


Impression for OOP

    In this course I’ve learned that Python is an object-oriented programming language, it is described that in OOP, ‘object’ is consisted of fields, which includes variables(contained in their object or class) and methods, which are the functions(contained in class). These independent objects are able to be reused, this ability is the feature of OOP. Actually, I have already learned something about Class in computer science 108 last semester, which helps me a lot to understand OOP but I am still a little bit confused about it. 

What I have already learned in class is that how to create different classes and define plenty of methods. And class has Inheritance, which means when different classes are called in other classes, they(subclass) inherit the properties from their original classes(parent class). When Danny was talking about OOP, I found that the built-in property() function in Python is hard to grasp. When I create an instance of Point, will it call property() function and then _set_coord(), _get_coord() are called? Does the self.coord have the same memory address as the Property object coord since there is only one “coord“ in the namespace? 

After going to Dannie's office hour before Term test 1, l got the answer of my questions. Access to coord is delegated to property, so _get_coord and _set_coord are called when I create an instance of Point. And self.coord and the Property coord both have the same memory address.

No comments:

Post a Comment