0% found this document useful (0 votes)
34 views2 pages

Adding Methods Dynamically in Python

The document explains how to dynamically add methods to objects and classes in Python, highlighting its usefulness in unit testing. It provides examples of adding a function as a method to an instance and a class, demonstrating the difference between instance-specific and class-wide methods. Additionally, it notes that methods automatically receive 'self' unless specified otherwise as class or static methods.

Uploaded by

vijayaselvi2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views2 pages

Adding Methods Dynamically in Python

The document explains how to dynamically add methods to objects and classes in Python, highlighting its usefulness in unit testing. It provides examples of adding a function as a method to an instance and a class, demonstrating the difference between instance-specific and class-wide methods. Additionally, it notes that methods automatically receive 'self' unless specified otherwise as class or static methods.

Uploaded by

vijayaselvi2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ADDING METHODS DYNAMICALLY IN PYTHON

 Dynamic nature of Python is we can do many things in runtime, like add


methods dynamically to an object or class.
 It is useful when writing unit tests.

Program to demonstrate adding a method to and object:

class Person(object):
pass
def play():
print "i'm playing!"
p = Person()
p.play = play
p.play()

 Note that play is just a function, it doesn’t receive self.


 There is no way to p knows that it’s a method.
 If we need self, you must create a method and then bind to the object.

from types import MethodType


class Person(object):
def __init__(self, name):
self.name = name
def play(self):
print "%s is playing!" % self.name
p = Person("igor")
p.play = MethodType(play, p)
p.play()
 In these examples, only the p instance will have play method, other instances
of Person won’t.
 To accomplish this we need to add the method to the class:

class Person(object):
def __init__(self, name):
self.name = name
def play(self):
print "%s is playing!" % self.name
Person.play = play
p1 = Person("igor")
p1.play()
p2 = Person("joh")
p2.play()

 Note that we don’t need to create a method with types.


 Method Type here, because all functions in the body of a class will become
methods and receive self, unless you explicit say it’s
a classmethod or staticmethod.

You might also like