Classes and objects(Object Oriented Programming ) In Python

Methods in OOP | Python

In this article, we learn about all the methods in OOP’s concept (in detail).

Methods:

The method is a function that is associated with an object. In python, a method is not a unique to the class instance. Any object can have methods
There are three types of methods in python. They are
· Instance method
· Class method
· Static method

Instance method:

an instance method is a very basic and easy method that we use regularly when we create classes in python.  we should create an object of the class if we wanted to print the instance attributes or methods

If we are using self as a function parameter or in front of a variable, that is nothing but the calling instance variable or method itself.

As we are working with instance variables, we use the self keyword.

Note: Instance variables are used with instance methods.

Example of Instance:

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method to access instance variable
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

The above method is an instance method used to display the student details.

Calling An Instance Method

We use an object and dot (.) operator to execute the block of code or action defined in the instance method.

  • First, create instance variables name and age in the Student class.
  • Next, create an instance method display() to print student name and age.
  • Next, create object of a Student class to call the instance method.
See also  Build a GUI with Tkinter and automate MS Word with Python

let’s see how to call an instance method show() to access the student object details such as name and age.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method access instance variable
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

# create first object
print('First Student')
Udaysk = Student("udaysk", 19)
# call instance method
Udaysk.show()

# create second object
print('Second Student')
Uday= Student("Uday", 18)
# call instance method
Uday.show()

OUTPUT:

First Student

Name: Udaysk Age: 19

Second Student

Name: Uday Age: 18

Class method:

There are two ways to create class methods in python:

  1. Using classmethod(function)
  2. Using @classmethod annotation

A class method can be called either using the class (such as C.f()) or using an instance (such as C().f()). The instance is ignored except for its class. If a class method is called from a derived class, the derived class object is passed as the implied first argument.

As we are working with ClassMethod we use the cls keyword. Class variables are used with class methods.

The classmethod() is an inbuilt function in Python, which returns a class method for a given function.

Create Class Method Using @classmethod Decorator:

Example:

from datetime import date

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

    @classmethod
    def calculate_age(cls, name, birth_year):
        # calculate age an set it as a age
        # return new object
        return cls(name, date.today().year - birth_year)

    def show(self):
        print(self.name + "'s age is: " + str(self.age))

Udaysk= Student(Udaysk, 2004)
Udaysk.show()

# create new object using the factory method
Uday= Student.calculate_age("Uday", 2003)
Uday.show()

OUTPUT:

Udaysk’s age is: 18
Uday’s age is: 19

Create class method using classmethod() function:

Example:

class Hotel:
    # class variable
    name = 'ABC Hotel'

    def hotel_name(cls):
        print(Hotel Name is :', cls.name)

# create class method
Hotel.hotel_name = classmethod(Hotel.hotel_name)

# call class method
Hotel.hotel_name()

Output:

See also  Get Wifi Password Using Python

Hotel Name is : ABC Hotel

Static method:

A static method can be called without an object for that class, using the class name directly. If you want to do something extra with a class, we use static methods.
We can directly call the static method by directly calling it by it’s class name.

A static method is a general utility method that performs a task in isolation. Inside this method, we don’t use instance or class variable because this static method doesn’t take any parameters like self and cls.

A static method is a general utility method that performs a task in isolation. Static methods in Python are similar to those found in Java or C++.

Example:

class Employee:
    @staticmethod
    def sample(x):
        print('Inside static method', x)

# call static method
Employee.sample(10)

# can be called using object
emp = Employee()
emp.sample(10)

The class method can be called using ClassName.method_name() as well as by using an object of the class.

A static method doesn’t have access to the class and instance-variables because it does not receive an implicit first argument like self and cls. Therefore it cannot modify the state of the object or class.

Any method we create in a class will automatically be created as an instance-method. We must explicitly tell Python that it is a static method using the @staticmethod decorator or staticmethod() function.

Syntax:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

To make a method a static method, ad@staticmethod decorator before the method definition.

The @staticmethod decorator is a built-in function decorator in Python to declare a method as a static method. It is an expression that gets evaluated after our function is defined.

See also  Free Python Data Science Course

In this example, we will create a static method gather_requirement() that accepts the project name and returns all requirements to complete under this project.

Static methods are a special case of methods. Sometimes, you’ll write code that belongs to a class, but that doesn’t use the object itself at all. It is a utility method and doesn’t need an object (self parameter) to complete its operation. So we declare it as a static method. Also, we can call it from another method of a class.

class Employee(object):

    def __init__(self, name, salary, project_name):
        self.name = name
        self.salary = salary
        self.project_name = project_name

    @staticmethod
    def gather_requirement(project_name):
        if project_name == 'ABC Project':
            requirement = ['task_1', 'task_2', 'task_3']
        else:
            requirement = ['task_1']
        return requirement

    # instance method
    def work(self):
        # call static method from instance method
        requirement = self.gather_requirement(self.project_name)
        for task in requirement:
            print('Completed', task)

emp = Employee('Kelly', 12000, 'ABC Project')
emp.work()

Output:

Completed task_1
Completed task_2
Completed task_3

Leave a Comment

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

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.