python,即时动态实现一个类
假设我有一个实现多种方法的类。我们希望用户选择在现有方法中运行哪些方法,或者他可以决定添加任何 on_the_fly 方法。
从示例中
class RemoveNoise():
pass
,可以根据需要添加方法,
RemoveNoise.raw = Raw()
RemoveNoise.bais = Bias()
etc
他甚至可以编写一个新方法
def new():
pass
,并添加 new()
方法
RemoveNoise.new=new
run(RemoveNoise)
run()
是一个评估此类类的函数。
我想保存 class_with_the_methods_used 并将此类链接到创建的对象。
关于如何在 python 中解决这个问题有任何提示吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以在运行时将函数添加到类中。
Functions can be added to a class at runtime.
无需解决,您只需执行即可。这是您的代码,需要进行一些小的更改:
就这么简单。 Python 很棒。
不过,我到底为什么需要这个?
There is no solving needed, you just do it. Here is your code, with the small changes needed:
It's that simple. Python is wonderful.
Why on earth you would need this is beyond me, though.
好吧,这里有一些代码可以满足我认为您要求的功能 - 尽管我不太确定当您写“我想保存 class_with_the_methods_used”时“保存”的含义。另请注意,如果用户输入来自不受信任的来源,则对用户输入使用
exec
语句可能会极其危险。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.