【问题标题】:Python, Django, using Import from inside of a class, can't seem to figure this outPython,Django,使用从类内部导入,似乎无法解决这个问题
【发布时间】:2010-09-14 22:21:49
【问题描述】:

我想在一个类中使用导入,然后由另一个类继承,这样我就不必在每个文件中手动定义我的导入。我正在尝试这样但它不起作用,任何建议表示赞赏:

class Djangoimports ():
    def __init__(self):
        from django.template import Context
        print Context


class Init1 (Djangoimports):
    def __init__(self):
        Djangoimports.__init__(self)

        self.c = Context(self.constructor_dict) # just example of trying to use the imported "Context"
>>>>> global name 'Context' is not defined

我已经尝试过尝试使用“self”的变体,但无法弄清楚如何在 import from 中适当地使用它,因为它与我通常使用“self”的类属性/方法不同

【问题讨论】:

    标签: python django class import


    【解决方案1】:

    这对我来说很好。

    但你最好这样做:

    >>> class Test(object):
    ...        from functools import partial
    ... 
    >>> Test().partial
    <type 'functools.partial'>
    

    请注意,按照自己的方式进行操作,您必须在每个实例的基础上初始化它们并分配给 self,如下所示:

    def Test(object):
        def __init__(self):
             from functools import partial
             self.partial = partial
    

    无论哪种方式,您现在都可以在该类的其他方法中访问bar,或者作为self.bar 的派生方法。

    【讨论】:

    • 谢谢,我想我明白你的意思了,但我不确定如何在继承导入器类的类中使用它
    • @Rick。您可以将其作为 self.bar 访问,因为它成为类命名空间的一部分。
    • 哦,好吧,我明白了,我自己应该已经抓住了:)...感谢您在这方面的帮助
    【解决方案2】:

    在 Python 中,导入只是添加到当前命名空间。从函数返回后,命名空间会丢失,但您可以保留将其附加到“self”的指针。

    你可以这样做:

    class Djangoimports ():
        def __init__(self):
            from django.template import Context
            self.Context = Context
    
    class Init1 (Djangoimports):
        def __init__(self):
            Djangoimports.__init__(self)
            self.c = self.Context(self.constructor_dict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2020-08-31
      • 1970-01-01
      相关资源
      最近更新 更多