Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 818
shaz Avatar asked Feb 25 '23 15:02

shaz


1 Answers

Functions can be added to a class at runtime.

class Foo(object):
  pass

def bar(self):
  print 42

Foo.bar = bar
Foo().bar()
like image 190
Ignacio Vazquez-Abrams Avatar answered Feb 28 '23 07:02

Ignacio Vazquez-Abrams