0

what is exactly bound method and unbound method in python. How does it differ when object is created?

i am beginner to python i wrote this small piece of code

   class newclass:
      def function1(self,var2):
        self.var2=var2
        print var2
        self.fun_var=var2

   newobject = newclass
   newobject.function1(64)

I am getting error like this

Traceback (most recent call last):
  File "basic_class.py", line 8, in <module>
    newobject.function1(64)
TypeError: unbound method function1() must be called with newclass instance as first argument (got int instance instead)

what is exactly bound method and unbound method in python

Vivek
  • 181
  • 3
  • 10

2 Answers2

2

The correct object initialization in Python is:

newobject = newclass()   # Note the parens

A bound method is an instance method, ie. it works on an object. An unbound method is a simple function that can be called without an object context. See this answer for a detailed discussion.

Note that in Python 3 unbound method concept is removed.

Community
  • 1
  • 1
Selcuk
  • 57,004
  • 12
  • 102
  • 110
2

In your case you should first create instance of newclass and then call function1.

class newclass:
  def function1(self,var2):
    self.var2=var2
    print var2
    self.fun_var=var2

newobject = newclass
newobject().function1(64)
ikhtiyor
  • 504
  • 5
  • 15