Create methods in python

Python Instance Methods Explained With Examples

In Python object-oriented programming, when we design a class, we use the instance methods and class methods.

Inside a Class, we can define the following two types of methods.

  • Instance methods: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods. It must have a self parameter to refer to the current object.
  • Class methods: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method. The class method has a cls parameter which refers to the class.

After reading this article, you’ll learn:

  • How to create and call instance methods
  • how to dynamically add or delete instance methods in Python

Table of contents

What is Instance Methods in Python

If we use instance variables inside a method, such methods are called instance methods. The instance method performs a set of actions on the data/value provided by the instance variables.

  • A instance method is bound to the object of the class.
  • It can access or modify the object state by changing the value of a instance variables
Читайте также:  Python apache wsgi настройка

When we create a class in Python, instance methods are used regularly. To work with an instance method, we use the self keyword. We use the self keyword as the first parameter to a method. The self refers to the current object.

Any method we create in a class will automatically be created as an instance method unless we explicitly tell Python that it is a class or static method.

Instance method in Python

Define Instance Method

Instance variables are not shared between objects. Instead, every object has its copy of the instance attribute. Using the instance method, we can access or modify the calling object’s attributes.

Instance methods are defined inside a class, and it is pretty similar to defining a regular function.

  • Use the def keyword to define an instance method in Python.
  • Use self as the first parameter in the instance method when defining it. The self parameter refers to the current object.
  • Using the self parameter to access or modify the current object attributes.

You may use a variable named differently for self , but it is discouraged since self is the recommended convention in Python.

Let’s see the example to create an instance method show() in the Student class to display the student details.

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)

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.

et’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') emma = Student("Jessa", 14) # call instance method emma.show() # create second object print('Second Student') kelly = Student("Kelly", 16) # call instance method kelly.show()
First Student Name: Jessa Age: 14 Second Student Name: Kelly Age: 16

Inside any instance method, we can use self to access any data or method that reside in our class. We are unable to access it without a self parameter.

An instance method can freely access attributes and even modify the value of attributes of an object by using the self parameter.

By Using self.__class__ attribute we can access the class attributes and change the class state. Therefore instance method gives us control of changing the object as well as the class state.

Modify Instance Variables inside Instance Method

Let’s create the instance method update() method to modify the student age and roll number when student data details change.

class Student: def __init__(self, roll_no, name, age): # Instance variable self.roll_no = roll_no self.name = name self.age = age # instance method access instance variable def show(self): print('Roll Number:', self.roll_no, 'Name:', self.name, 'Age:', self.age) # instance method to modify instance variable def update(self, roll_number, age): self.roll_no = roll_number self.age = age # create object print('class VIII') stud = Student(20, "Emma", 14) # call instance method stud.show() # Modify instance variables print('class IX') stud.update(35, 15) stud.show()
class VIII Roll Number: 20 Name: Emma Age: 14 class IX Roll Number: 35 Name: Emma Age: 15

Create Instance Variables in Instance Method

Till the time we used constructor to create instance attributes. But, instance attributes are not specific only to the __init__() method; they can be defined elsewhere in the class. So, let’s see how to create an instance variable inside the method.

class Student: def __init__(self, roll_no, name, age): # Instance variable self.roll_no = roll_no self.name = name self.age = age # instance method to add instance variable def add_marks(self, marks): # add new attribute to current object self.marks = marks # create object stud = Student(20, "Emma", 14) # call instance method stud.add_marks(75) # display object print('Roll Number:', stud.roll_no, 'Name:', stud.name, 'Age:', stud.age, 'Marks:', stud.marks)
Roll Number: 20 Name: Emma Age: 14 Marks: 75

Dynamically Add Instance Method to a Object

Usually, we add methods to a class body when defining a class. However, Python is a dynamic language that allows us to add or delete instance methods at runtime. Therefore, it is helpful in the following scenarios.

  • When class is in a different file, and you don’t have access to modify the class structure
  • You wanted to extend the class functionality without changing its basic structure because many systems use the same structure.

Let’s see how to add an instance method in the Student class at runtime.

We should add a method to the object, so other instances don’t have access to that method. We use the types module’s MethodType() to add a method to an object. Below is the simplest way to method to an object.

import types class Student: # constructor def __init__(self, name, age): self.name = name self.age = age # instance method def show(self): print('Name:', self.name, 'Age:', self.age) # create new method def welcome(self): print("Hello", self.name, "Welcome to Class IX") # create object s1 = Student("Jessa", 15) # Add instance method to object s1.welcome = types.MethodType(welcome, s1) s1.show() # call newly added method s1.welcome()
Name: Jessa Age: 15
Hello Jessa Welcome to Class IX

Dynamically Delete Instance Methods

We can dynamically delete the instance method from the class. In Python, there are two ways to delete method:

By using the del operator

The del operator removes the instance method added by class.

In this example, we will delete an instance method named percentage() from a Student class. If you try to access it after removing it, you’ll get an Attribute Error.

class Student: # constructor def __init__(self, name, age): self.name = name self.age = age # instance method def show(self): print('Name:', self.name, 'Age:', self.age) # instance method def percentage(self, sub1, sub2): print('Percentage:', (sub1 + sub2) / 2) emma = Student('Emma', 14) emma.show() emma.percentage(67, 62) # Delete the method from class using del operator del emma.percentage # Again calling percentage() method # It will raise error emma.percentage(67, 62) 
Name: Emma Age: 14 Percentage: 64.5 File "/demos/oop/delete_method.py", line 21, in del emma.percentage AttributeError: percentage

By using the delattr() method

The delattr() is used to delete the named attribute from the object with the prior permission of the object. Use the following syntax to delete the instance method.

  • object : the object whose attribute we want to delete.
  • name : the name of the instance method you want to delete from the object.

In this example, we will delete an instance method named percentage() from a Student class.

emma = Student('Emma', 14) emma.show() emma.percentage(67, 62) # delete instance method percentage() using delattr() delattr(emma, 'percentage') emma.show() # Again calling percentage() method # It will raise error emma.percentage(67, 62)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Comments

# delete instance method percentage() using delattr()
delattr(emma, ‘percentage’) The above is not working it gives an error.
Traceback (most recent call last):
File “”, line 1, in
delattr(emma, ‘percentage’)
AttributeError: percentage,

delattr(emma, ‘percentage’) #Relpace emma with Student because u have to type the class name not the class object delattr(Student,’percentage’)

Источник

Working with Methods in Python

Book image

Methods are simply another kind of function that reside in classes. You create and work with methods in Python in precisely the same way that you do functions, except that methods are always associated with a class. You can create two kinds of methods: those associated with the class itself and those associated with an instance of a class. It’s important to differentiate between the two.

Creating class methods

class MyClass: def SayHello(): print("Hello there!")

Working with methods in Python

A class method can work only with class data. It doesn’t know about any data associated with an instance of the class. You can pass it data as an argument, and the method can return information as needed, but it can’t access the instance data. As a consequence, you need to exercise care when creating class methods to ensure that they’re essentially self-contained.

Creating instance methods

An instance method is one that is part of the individual instances. You use instance methods to manipulate the data that the class manages. As a consequence, you can’t use instance methods until you instantiate an object from the class.

All instance methods accept a single argument as a minimum, self . The self argument points at the particular instance that the application is using to manipulate data. Without the self argument, the method wouldn’t know which instance data to use. However, self isn’t considered an accessible argument — the value for self is supplied by Python, and you can’t change it as part of calling the method.

  1. Open a Python Shell window. You see the familiar Python prompt.
  2. Type the following code (pressing Enter after each line and pressing Enter twice after the last line):
class MyClass: def SayHello(self): print("Hello there!")

Instance methods in Python

About This Article

This article is from the book:

Источник

Оцените статью