Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add member function to an instance of a class in Python

Tags:

python

When I do the following:

class C:
 pass

def f( self ):
 print self

a = C()

a.f = f

a.f()

I get the following error at the line a.f(): TypeError: f() takes exactly 1 argument (0 given)

The problem appears to be that when f is added to the instance, a, it is treated like a function that is stored inside of a, rather than an actual member function. If I change a.f() to a.f(a), then I get the intended effect, but is there a way to make python interpret the original example this way? In other words, is there a way to add a member function to an instance of a class at runtime?

Thanks

like image 892
Harold Forrest Avatar asked May 25 '11 01:05

Harold Forrest


People also ask

How do you create an instance of a class dynamically in Python?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

How do I add a method to an existing class in Python?

Use the types. MethodType function to add a method to an existing object instance, e.g. my_inst. increase_salary = types.

How do you create a dynamic function in Python?

Method 1: exec() It's the perfect way to dynamically create a function in Python! ? Python's built-in exec() executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime.


2 Answers

You should put f in the class, not in the instance...

 class C:
     pass

 def f(self):
    print(self)

 a = C()
 C.f = f
 a.f()

For the interpreter myObject.foo() is the same as myClass.foo(myObject) when the object doesn't hold anything named foo, but a function placed inside a object is just a function.

like image 20
JBernardo Avatar answered Sep 16 '22 18:09

JBernardo


For Python 2.X you can use:

import types
class C:
    pass

def f(self):
    print self

a = C()
a.f = types.MethodType(f,a)
a.f()

For Python 3.X:

import types
class C(object):
    pass

def f(self):
    print(self)

a = C()
a.f = types.MethodType(f,a)
a.f()
like image 166
GWW Avatar answered Sep 16 '22 18:09

GWW