python-如何动态创建一个基于从文件中读取的字符串的名称的函数? [英] python - how can I dynamically create a function with a name based on a string read in from a file?
本文介绍了python-如何动态创建一个基于从文件中读取的字符串的名称的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含字符串"unpredictable_words"的文件.我想读这个字符串,然后定义一个函数,如下所示:
Let's say I have a file containing the string "unpredictable_words". I would like to read in this string and then define a function as follows:
def test_unpredictable_words(self):
do_important_stuff()
然后我想将此函数注入到类定义中,以便可以在此类的任何实例上调用此函数.
I would then like to inject this function into a class definition so that this function can be called on any instances of this class.
我该怎么做?
我对这个答案有些了解- https://stackoverflow.com/a/8160676/1701170 -但是我不认为它确实可以满足我的要求,或者至少我不了解正在发生的事情.
I looked a bit at this answer - https://stackoverflow.com/a/8160676/1701170 - but I don't think it does what I want, exactly, or at least I can't understand what is going on.
推荐答案
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
>>> def injected(self):
... print 'injected'
...
>>> class A(object):
... pass
...
>>> A.injected = injected
>>> a = A()
>>> a.injected()
injected
>>> def func2(self):
... print 'func2'
...
>>> setattr(A, 'injected2', func2)
>>> a.injected2()
func2
>>>
这篇关于python-如何动态创建一个基于从文件中读取的字符串的名称的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文