Python dynamically implement the onthefly class

Assuming I have a class that implements several methods. We want the user to choose which methods to run among existing methods, or he can decide to add any on_the_fly method.

from an example

class RemoveNoise(): pass 

then methods are added as desired

 RemoveNoise.raw = Raw() RemoveNoise.bais = Bias() etc 

he can even write a new one

 def new(): pass 

and also add the new() method

 RemoveNoise.new=new run(RemoveNoise) 

run() is a function that evaluates such a class.

I want to save the_with_the_methods_used class and associate this class with the created object.

Any tips on how to solve this in python?

+4
source share
3 answers

Functions can be added to the class at runtime.

 class Foo(object): pass def bar(self): print 42 Foo.bar = bar Foo().bar() 
+6
source

There is no need for a solution, you just do it. Here is your code with a few changes:

 class RemoveNoise(): pass RemoveNoise.raw = Raw RemoveNoise.bias = Bias def new(self): pass RemoveNoise.new=new instance = RemoveNoise() 

It is so simple. Python is wonderful.

Why don't you need it to be taller than me.

+2
source

Well, here is some code that does what I think you are asking for - although I'm not quite sure what you meant by " save " when you wrote "I want to save class_with_the_methods_used". Also note that using the exec statement when entering a user can be extremely dangerous if it comes from an untrusted source.

 import copy # an empty "template" class class Generic(): pass # predefined functions that create common methods def Raw(): def raw(self): print 'in Raw method of instance', id(self) return raw def Bias(): def bias(self): print 'in Bias method of instance', id(self) return bias def user_new_function(definition): tempdict = {} exec definition in tempdict return tempdict['new'] # create a new class RemoveNoise = copy.deepcopy(Generic) RemoveNoise.__name__ = 'RemoveNoise' # change the class name of the copy # add a couple of predefined methods RemoveNoise.raw = Raw() RemoveNoise.bias = Bias() # add user defined 'new' method user_new_def = """\ def new(self): print 'in user defined method "new" of instance', id(self) """ RemoveNoise.new = user_new_function(user_new_def) # create and use an instance of dynamically defined class instance = RemoveNoise() print 'RemoveNoise instance "{}" created'.format(id(instance)) # RemoveNoise instance "11974736" created instance.raw() # in Raw method of instance 11974736 instance.bias() # in Bias method of instance 11974736 instance.new() # in user defined method "new" of instance 11974736 
0
source

All Articles