Classes in Python

Classes in Python:

Example For a Python Class

                       Image Courtesy: brownpau, flickr License Creative commons

Through classes Python support Object Oriented Programming.
In object oriented programming classes represent concepts.
Objects are instantiated as replicas of the defined classes.

e.g., ComplexNumber is a class. ComplexNumber1, ComplexNumber2..ComplexNumberN are objects created with a ComplexNumber class. 

Objects are also called as instances.
In the below sections, let us understand how to create classes and objects in Python.

How to create a class in Python?


A class in python is defined with the keyword class, followed by the class name and a colon.
Any meaningful python class will have the following defined:
    A Constructor        - To create and initialise objects
    Set of Attributes    - To represent the properties of a class
    Set of Methods     - To provide the behaviour of the objects

Definition of a class introduces a new type into the system. Classes are also called as User Defined Types.

Example:
 

class MarkerPen:

    myInkColor = "Black";

    myState    = "CapClosed";

 

    def __init__(self, aInkColor_in):

        self.myInkColor = aInkColor_in

   

    def open():

        myState = "CapRemoved";

       

    def close():

        myState = "CapClosed";

   

    def drawLine():

        print("Line drawn from {} to {}".format(pointA_in, pointB_in))

In this example, a simple Python class called  MarkerPen is defined.
Inside the class, two attributes of the class called myInkColor, myState are defined. The methods open(), close() and drawLine() are provided.  Defining the method is similar to defining the functions. When functions
are defined for a class they are called methods. In object oriented parlance  a method is also called as the behaviour of an object.


Creating Objects in Python:

Objects are instances of a class. They are instantiated using one of the constructors defined for a class.

A constructor is a method defined inside the class. The main responsibility of the constructor is to create an object. 
The constructor initialises an object with necessary attributes. Let us create an object using the MarkerPen constructor.

# Create a green colored MarkerPen object with the state, cap open

GreenPen = MarkerPen("Green", "CapOpen") # Call to constructor

 

# Create a red colored MarkerPen object with the state, cap open

RedPen = MarkerPen("Red", "CapOpen") # Call to constructor

 

# Create a MarkerPen object with default attributes

BlackPen = MarkerPen()

All the GreenPen, RedPen and BlackPen are objects of type MarkerPen.
To be more precise - the GreenPen, RedPen and BlackPen are references to objects of type MarkerPen. 

How to call methods on objects in Python?

Once objects are created, methods on those objects can be called using the "." operator.The method invocations below are all, calls to the method drawLine() on the created Objects. 

GreenPen.drawLine();

RedPen.drawLine();

BlackPen.drawLine();

 

Complete Example using classes and objects in Python:

Here is the complete example program in Python involving classes and objects. This program,

  1. Defines a class
  2. Creates objects
  3. Calls methods on object

class MarkerPen:

    myInkColor=""

    myState=""

 

    def __init__(self, aInkColor_in="Black", aState_in="CapClosed"):

        self.myInkColor = aInkColor_in

        self.myState = aState_in

   

    def open(self):

        myState = "CapRemoved"

       

    def close(self):

        myState = "CapClosed"

   

    def drawLine(self):

        print("I just drawn a line")

   

    def printState(self):

        print("I am a {} pen".format(self.myInkColor))

        print("My current cap position is {} ".format(self.myState))

 

 

# Create a green colored MarkerPen object with the state, cap open

GreenPen = MarkerPen("Green", "CapOpen") # Call to constructor

 

# Create a red colored MarkerPen object with the state, cap open

RedPen = MarkerPen("Red", "CapOpen") # Call to constructor

 

# Create a MarkerPen object with default attributes

BlackPen = MarkerPen()

BlackPen.printState()

BlackPen.drawLine()

 

Output:

I am a Black pen

My current cap position is CapClosed

I just drawn a line

The first two lines of the output shows the state of the object printed through printState() Method.
The third line shows a line printed from the drawLine() method - which represents the behaviour of the object. 


Copyright 2024 © pythontic.com