开发者

python, dynamically implement a class onthefly

Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on_the_fly.

from example

class RemoveNoise():
       pass

then methods are added as wanted

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 class_with_the_methods_used and link this class to the object created.

Any hints on how to solve this in python?


Functions can be added to a class at runtime.

class Foo(object):
  pass

def bar(self):
  print 42

Foo.bar = bar
Foo().bar()


There is no solving needed, you just do it. Here is your code, with the small changes needed:

class RemoveNoise():
       pass

RemoveNoise.raw = Raw
RemoveNoise.bias = Bias

def new(self):
   pass

RemoveNoise.new=new

instance = RemoveNoise()

It's that simple. Python is wonderful.

Why on earth you would need this is beyond me, though.


Well, here's some code that does what I think you're asking for -- although I'm not really sure what you meant by "save" when you wrote "I want to save the class_with_the_methods_used". Also note that using an exec statement on user input 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜