我希望能够在对象实例化期间动态加载实例方法。根据我的设计,默认行为是在基类中编码的。然而,如果在对象安装过程中满足一定的条件,动态地用另一段代码更改此行为。这就是我这样做:
默认行为编码为first.py
:
class First(object):
def __init__(self, p):
p = str(p)
#The decision whether or not to perform default action is done
#in the following try/except block. In reality this block
#is more complicated
#and more checks are performed in order to assure proper work
try:
strImport = "__import__('module%s')"%p
e = eval(strImport, {}, {})
if not hasattr(e, p):
raise ImportError()
except ImportError:
e = None #default behaviour
if e is not None:
self.act = getattr(e, p)(p).act #special behaviour
self.p = p
def act(self):
print 'Default behaviour'
import cPickle as pickle
if __name__ == '__main__':
print 'first'
first = First('f')
first.act()
pickle.dump(first, open('first.dump', 'w'))
print 'third'
third = First('Third')
third.act()
pickle.dump(third, open('third.dump', 'w'))
在上面的代码中,first
和third
都执行默认操作。我可以改变
moduleThird.py
文件,修改third
的行为
from temp import First
class Third(First):
def __init__(self, p):
p = 'Third *** %p'
print 'third init'
super(self.__class__, self).__init__(p)
def act(self):
super(self.__class__, self).act()
print 'Third acted'
添加此文件后,third
改变其行为。但是我不是由于以下错误,无法pickle生成的对象:
Traceback (most recent call last):
File "C:temptemp.py", line 35, in <module>
pickle.dump(fff, open('fff.dump', 'w'))
File "C:Python26libcopy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
很明显,动态加载方法Third.act
导致了pickle的问题。为了获得可选择的对象(以及更优雅的代码),我需要如何改变我的方法?
有没有更好的方法来实现我的目标?
如果您按照以下方式更改代码,那么它应该可以工作:
class First(object):
def __init__(self, p):
p = str(p)
#The decision whether or not to perform default action is done
#in the following try/except block. In reality this block
#is more complicated
#and more checks are performed in order to assure proper work
try:
strImport = "__import__('module%s')"%p
print strImport
e = eval(strImport, {}, {})
if not hasattr(e, p):
raise ImportError()
self.override_obj = getattr(e, p)(p)
except ImportError:
e = None #default behaviour
self.override_obj = None
self.p = p
def act(self):
if self.override_obj:
return self.override_obj.act()
else:
print 'Default behaviour'