如何替换ORM类 - 所以它不应该导致递归!!!
问题:
原始类具有超级调用,当它被替换时 - 它会导致自我继承并导致最大递归深度超过异常
即,orm正在调用super(orm,self)....并且orm已被另一个继承原始orm的类所取代....
addons __init__.py osv run_app.py
./addons:
__init__.py test_app1.py test.py
./osv:
__init__.py orm.py
class orm_template(object):
def __init__(self, *args, **kw):
super(orm_template, self).__init__()
def fields_get(self, fields):
return fields
def browse(self, id):
return id
class orm(orm_template):
def __init__(self, *args, **kw):
super(orm, self).__init__(*args, **kw)
def fields_get(self, fields, context = None):
return super(orm, self).fields_get(fields)
def read(self, fields):
return fields
import test
def main(app):
print "Running..."
__import__(app, globals(), locals())
from osv import orm
import osv
class orm(orm.orm):
def __init__(self, *args, **kw):
super(orm, self).__init__(*args, **kw)
def fields_get(self, *args, **kw):
print "my fields get................."
return super(orm, self).fields_get(*args, **kw)
osv.orm.orm = orm
print "replaced.........................."
from osv.orm import orm
class hello(orm):
_name = 'hellos'
def __init__(self, *args, **kw):
super(hello, self).__init__(*args, **kw)
print hello('test').fields_get(['name'])
import addons
addons.main('test_app1')
>>>python run_app.py
replaced..........................
Running...
...
...
super(orm, self).__init__(*args, **kw)
RuntimeError: maximum recursion depth exceeded
我见过类似的question
答案 0 :(得分:5)
您的addons/test.py
需要获取并保留对原始orm.orm
的引用,并使用该代码而不是替换版本。即:
from osv import orm
import osv
original_orm = osv.orm
class orm(original_orm):
def __init__(self, *args, **kw):
super(orm, self).__init__(*args, **kw)
def fields_get(self, *args, **kw):
print "my fields get................."
return super(orm, self).fields_get(*args, **kw)
osv.orm.orm = orm
print "replaced.........................."
所以monkeypatched-in类继承自原始而不是自身,就像你在设置中一样。顺便说一句,如果你可以通过更好地设计osv
模块来避免猴子修补(例如用w / setter函数设置什么是orm)你会更快乐; - )。