Python class and object tutorial with example

class and object are basic concept in object-oriented programming languages.a class is a collection of functions and variables, class is written by a programmer and should followed by a standard structure. object is simple an instance of a class.In this article we are going elaborate Python class and object tutorial with example.class in python is created by the keyword class.

So now we know the basic of a class,still wondering why we are using it and what are the advantages of class in python.

advantages of class in python

  • Re-usability
  • Data Redundancy
  • Security
  • Code Maintenance
  • Design Benefits. etc

Python class syntax

class Name_of_the_class:
    # Statement-1
    # Statement-N

Python class and object tutorial with example code

class calculator:
   def sum(a, b):

     return a + b
   def multip(a, b):

     return a * b
   def div(a,b):

     return b / a
cal= calculator()

Python class and object tutorial with example

Object of class in python

We know that object is an instance of a class, in simple Object of class in python is the copy of a class with actual values in it.In the above example cal is the object of the class calculator.we can create n number of object for a single class .example cal1= calculator() is the other instance of the class calculator() like this we can create n object for the class calculator().

__init__ method

__init__ method is a method in python ,it is like exactly like constructor concept in PHP or Java,__init__ is automatically called when an object of that class is created.__init__ method is normally used to initialize the data in a class.

Example of __init__ method in python

class Employee:
    # init method or constructor 
    def __init__(self, employee_id,name):
        self.employee_id = employee_id = name
    # Sample Method 
    def welome_emp(self):
        print('Hello, welcome', self.employee_id, 'Your EMployee Id id',
p = Employee('Anamika','Emp1009')

My Thought

Your email address will not be published. Required fields are marked *