我希望能够在对象实例化期间动态加载实例方法。根据我的设计,默认行为在基类中编码。但是,如果 在物体实例化期间,我会动态地满足某些条件 用另一段代码改变这种行为。这是怎么回事 我这样做:
默认行为以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
都执行默认操作。我可以改变
third
通过添加文件moduleThird.py
的行为,如下所示:
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
会更改其行为。不过我不是
由于以下错误,无法腌制结果对象:
Traceback (most recent call last):
File "C:\temp\temp.py", line 35, in <module>
pickle.dump(fff, open('fff.dump', 'w'))
File "C:\Python26\lib\copy_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的问题。我如何才能更改我的方法以获得可选择的对象(以及更优雅的代码)?
有没有更好的方法来实现我的目标?
答案 0 :(得分:1)
如果您按如下方式更改代码,那么它应该有效:
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'