如果没有多余的imp,则无法定位对象方法中引用的对象

2024-06-10 13:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在传递单个参数时呈现一个Jinja2模板。此参数是具有引用第二个对象的方法的对象的实例。我传递给Jinja2的对象存储在一个模块中,而引用的对象存储在第二个模块中。渲染在第三个模块中进行。当第一个对象的方法引用第二个对象(global name ... is not defined)时,原始代码会出错。这种方法在Jinja2之外运行良好。下面是一个简单的例子来设置场景

jinja2渲染模块如下所示:

from jinja2 import Template
from module1 import *
from module2 import *

def return_rendered():
    otr = ObjectToRender()
    otr.name = 'Just making the instance special!'

    temp_str = open('template.html', 'r')
    template = Template(temp_str.read())
    temp_str.close()

    return template.render(otr=otr)

模板如下所示:

<p>Here is the output from a super cool method!<p>
{{ otr.get_a_cool_name() }}

要渲染的对象:

# module1
class ObjectToRender(object):
    def __init__(self):
        self.name = ''

    def get_a_cool_name(self):
        rc = ReferencedClass() # fails here with "global name 
                               # 'ReferencedClass' is not defined"
        return rc.make_cool(self.name)

from module2 import *

以及引用的类:

# module2
from module1 import *
class ReferencedClass(object):
    def __init__(self):
        self.cool_str = 'SUPER COOL'

    def make_cool(self, in_str):
        return in_str + self.cool_str

您会注意到我已经将模块1和模块2“相互导入”。这里显然没有必要,但在我的用例中是这样的。无论如何,在使用ReferencedClass之前,通过再次导入第二个类,我就可以实现这一点。看起来是这样的:

# module1
class ObjectToRender(object):
    def __init__(self):
        self.name = ''

    def get_a_cool_name(self):
        from module2 import ReferencedClass
        rc = ReferencedClass() # it works! 
        return rc.make_cool(self.name)

from module2 import *

所以,我没有真正理解为什么一开始就不起作用。。。经典。有人知道我为什么要第二次导入这个类吗


Tags: 模块对象namefromimportselfreturndef