Class keyword in Python

Overview

  • The keyword class is fundamental to object oriented programming in Python.

 

  • The class keyword is used to define any concept e.g., Complex Number, UI Window, Sparse Matrix and so on which are instantiated using their definitions.

 

  • Methods and attributes can be defined for a class, which correspond to the behavior and state of an instance.

 

  • Through class keyword a new user defined type is introduced into the Python Program.

 

  • In Python, a concrete class defined is used to instantiate any number objects of the same type as the class.

 

  • An abstract class acts as a base class for derived classes and provides a common abstraction or a common interface for the derived classes.

 

  • In the picture below moulds of dolls are varying sizes are kept. Just like actual dolls are manufactured using these moulds the objects are instantiated using the classes.

A class acts a mould to create instances of the class

Picture Courtesy: Joel Kramer

  • Multiple inheritance is supported in Python through which a specialized concept or class is created by deriving from more than one class.

Example:

  • This Python example defines a class NoteBook representing a primitive notebook.

 

  • The Python program also instantiates the NoteBook class creating a NoteBook object.

 

class NoteBook:

    myPageCount = 0;

    myTitle     = "";

    myCoverOpen = False

    myCurrentPage = 0;

       

    def __init__(self, pageCount, title):

        self.myPageCount    = pageCount

        self.myTitle        = title

 

        self.myCoverOpen            = False

        self.myCurrentPage          = 1

   

    def FlipPage(direction):

        self.myCoverOpen         = True

        self.myCurrentPage       = self.myCurrentPage+1 # forward flip

 

nb = NoteBook(60, "Python Programming")

 

print("Page Count: %s"%(nb.myPageCount))

print("Page Title: %s"%(nb.myTitle))

 

 

Output:

Page Count: 60

Page Title: Python Programming

 


Copyright 2024 © pythontic.com