Lesson 10 – Python classes and objects

  • Creating a class

    To create a class in Python use the keyword class:

    class MyClass:
    x = 15
    y = 20

    Creating object
    Once the class is defined, next step to object (instance) of that class.  Here, we are creating object (p1), by invoking constructor of the class.
    Default constructor is the class name itself, with empty parenthesis i.e MyClass()
    p1 = MyClass()
    print(p1.x + p1.y)

    The __init__()  function

    All classes have a function called __init__(), which is invoked when the class is being instantiated

    class Student:
      def __init__(self, name, grade):
        self.name = name
        self.grade = grade




    The self parameter

    The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

    This does not have  to be self, you can name it the way, you want.  For example, it can be xyz. The first parameter is always this.

    Class methods  (functions)

    One can define new functions inside a class.

    For example, to print total marks of the student, we will define a new function in the below class

    class Student:
      def __init__(self, name, grade,mathsmarks,englishmarks):
        self.name = name
        self.grade = grade
        self.mathmarks = mathsmarks
        self.englishmarks = englishmarks

      def printmarks(abc):     # It need not be self, this can be any name like abc
        totalmarks = abc.mathmarks + abc.englishmarks
        print(“Total marks:”)



    Modifying the object attribute value

    Example: If you want to modify englishmarks to 98, then 

    s1.englishmarks = 98


    Deleting the object attributes

    If you want to delete a particular attribute from an object

    del s1.englishmarks

    This deletes the englishmarks attribute in the s1 object


    Deleting the object

    You can delete the object using del  command


    del s1   # This deletes the student s1