How Do You Use a Bound Method in Python?

Problem scenario
You want to write a Python program with a bound method.  What should you do?

Solution
This program uses a bound method.  The method funtest() is bound to objects that are members of the class "widgetfactory".  You cannot use the method without it being bound to this class.  (If you uncomment out the last line, you'll see it is a bound method and not an unbound method; the program will fail if you uncomment out the last line.)

#!/usr/bin/env python

class widgetfactory:
  def __init__(self):
    pass

  def funtest(self):  # This is a public method.
    print('This widget is working!')

goodwidget = widgetfactory()
goodwidget.funtest()
#funtest()     # This function (if uncommented out) will not work.  It must be bound to an object of the class "widgetfactory".

Leave a comment

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