Concept of Class, Method and Objects

Class

The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax for creating Class

  
  	class ClassName:
    	      {Statement Here}
  

Let's go through the example Suppose Employee is a class. Employee Has an atttributes Name, email, Address and Salary.

  
    class Employee:
	# Here __init__() is a constructor.Constructors are generally used for instantiating an object.
    The task of constructors is to initialize(assign 	values) to the data members of the class when an object of class is created.
    In Python the __init__() method is called the constructor and is always called when an object is created.
    def __init__(self):
        
  

Objects

The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.When we define a class, it needs to create an object to allocate the memory. Consider the following example.

  
  class Employee:
    def __init__(self, name, email, address, salary):#parameterize constructor
        self.name = name
        self.email = email
        self.address = address
        self.salary = salary
   amrit=Employee("Amrit","amritach222@gmail.com","Pokhara","60000")
   #Here amrit is a object of class Employee.
  	
  

Methods

A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences. The method is implicitly used for an object for which it is called. The method is accessible to data that is contained within the class.

  
  class Employee:
    def __init__(self, name, email, address, salary):#parameterize constructor
        self.name = name
        self.email = email
        self.address = address
        self.salary = salary
    def increaseSalary(self):
        self.salary=self.salary*1.4
   amrit=Employee("Amrit","amritach222@gmail.com","Pokhara",60000)
   #Here amrit is a object of class Employee.
   amrit.increaseSalary()# Invoke class method using object of class
   print(amrit.salary)
  	
  

classMethods

If we want to change the value of class variable then we need to create a class method which can able to update the variable of a class.Let's create the class Method.For this we need use a decorator as shown in below program by using @ sign:

  
  class Employee:
  # Create salary increment variable function
    increment = 10
    def __init__(self, name, email, address, salary):#parameterize constructor
        self.name = name
        self.email = email
        self.address = address
        self.salary = salary
    def increaseSalary(self):
        self.salary=self.salary*1.4
     @classmethod
    def change_increment(cls, amount):  # it takes two argument
        cls.increment = amount
   amrit=Employee("Amrit","amritach222@gmail.com","Pokhara",60000)
   print(amrit.salary)
   Employee.change_increment(3.4)
   amrit.increaseSalary()
   print(amrit.salary)
  	
  

CalssMethod as an alternative constructor

We can make a ClassMethod as an alternative constructor due to which we don't need to call the self argument, when we don't need to access the instances of class then we use classmethod.

  
  class Employee:
    def __init__(self, name, email, address, salary):#parameterize constructor
        self.name = name
        self.email = email
        self.address = address
        self.salary = salary
    @classmethod
    def from_str(cls,emp_string):
        name,email,address,salary=emp_string.split(",")
        return cls(name,email,address,salary)
 
   santosh = Employee.from_str("Santosh Rana,santosh33@gmail.com,India,56000")
   print(santosh.email)	
  

SataticMethod

Static methods, much like class methods, are methods that are bound to a class rather than its object.They do not require a class instance creation. So, they are not dependent on the state of the object. The difference between a static method and a class method is:

  • Static method knows nothing about the class and just deals with the parameters.
  • Class method works with the class since its parameter is always the class itself.
  • Static methods have a limited use case because, like class methods or any other methods within a class, they cannot access the properties of the class itself.However, when you need a utility function that doesn't access any properties of a class but makes sense that it belongs to the class, we use static functions.

      
      class Employee:
        def __init__(self, name, email, address, salary):#parameterize constructor
            self.name = name
            self.email = email
            self.address = address
            self.salary = salary
        # Lets create a static method. For creating static method we use a decorator as shown below 
        @staticmethod
        def isOpen(day):
           if(day=="Saturday"):
               return False
           else:
               return True
      print(Employee.isOpen("Monday"))#Then it returns True
      
    

    Comments

    Post a Comment