[pyhon] Object Oriented Programming(2)


Class design


Here, let's design our own class and defined object methods.

First example (2D point class)

  • This class will require a constructor (to be able to create instances of the class
  • couple of accessors that get the x, y coordinate of the point
  • mutator to move the point by a certain distance
  • import math
    
    class Point(object):
    
    	def __init__(self, x, y):
        	"""Construct a point object based on (x, y) coordinates.
    	Parameters:
    	x (float): x coordinate in a 2D cartesian grid. y (float): y coordinate in a 2D cartesian grid.
    	"""
        
        	    self._x = x
                self._y = y
          	
            def x_cord(self):
                """
                returns current x position of an object
                """
                return self.x
                
            def y_cord(self):
                """
                returns current y position of an object
                """
                return self.y
            
            def move(self, dx, dy):
                """
                moves current position to new given x, y coordinate position
                
                Parameters:
                    dx(int): new x coordinate
                    dy(int): new y coordinate
                """
                
                self.x += dx
                self.y += dy
    Class definition starts with keyword class, followed by class name and (object):
  • here, note the functions that are declared inside the class block.
  • they are the method definition for the class
  • Basic definition syntax

    class Classname(object):
        """comment"""
        def method_1(self, [args]):
            method_1 body
        
        def method_2(self, [args]):
            method_2 body
        
        def method_3(self, [args]):
            method_3 body
    Creates a class called classname to represent the ADT specified. The methods of the class are , method_1 , method_2 and so on.

    Using object method

    p = Point(2, -3)
    
    p.x_cord()
    >> 2
    
    p. y_cord()
    >> -3
    
    --------------------------------------
    p.move(1, 2)
    
    p.x_cord()
    >> 3
    
    p.y_cord()
    >> -1