Python add method to object

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
Читайте также:  Css card with button

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’)

Источник

How To Add A Method To An Existing Object Instance In Python?

Add a method to an existing object instance in Python

If you are looking for an instruction to add a method to an existing object instance in Python, keep reading our article. Today, we will provide some methods to show you how to do it.

Add a method to an existing object instance in Python

Use the function __get__()

In the Python programming language, the function __get__() can be used to define a dynamic method, attribute, or value. When declaring the function in a class, its performance is to return the value. We can add a method to an existing object when declaring the function outer the class.

Detailed implementation in the following code:

# Create an object class class Student: def __init__(self, name, age, subject): self.name = name self.age = age self. subject = subject def getName(self): return self.name def getAge(self): return self.age # Initialize an object std1 = Student("John", 15, "Calculus") # Create a new method def getSubject(self): return self.subject # Add the method to the object std1 std1.getSubject = getSubject.__get__(std1) print(std1.getSubject())

Use types.MethodType

Types.MethodType is a method that belongs to the library types and enables users to define a new method for an existing object. This way, an existing object can use a new-defined method as the initial method in the object class.

object.newMethod = types.MethodType(newMethod, object)

import types # Create an object class class Student: def __init__(self, name, age, subject): self.name = name self.age = age self. subject = subject def getName(self): return self.name def getAge(self): return self.age # Initialize an object std1 = Student("John", 15, "Calculus") # Create a new method def getSubject(self): return self.subject # Add the method to the object std1 std1.getSubject = types.MethodType(getSubject, std1) print(std1.getSubject())

Use functools.partial

The module “functools” provides the type partial returning the object that operates as a function called. When using this way, a partial function is applied to the object and makes the object have a method similar to methods inside the class object.

from functools import partial # Create an object class class Student: def __init__(self, name, age, subject): self.name = name self.age = age self. subject = subject def getName(self): return self.name def getAge(self): return self.age # Initialize an object std1 = Student("John", 15, "Calculus") # Create a new method def getSubject(self): return self.subject # Add the method to the object std1 std1.getSubject = partial(getSubject, std1) print(std1.getSubject())

Summary

Our tutorial provides some detailed examples to add a method to an existing object instance in Python. We hope you gain much knowledge from our article. If you have any troubles, do not hesitate to give us your questions. Thanks for reading!

Maybe you are interested:

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Источник

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