Skip to main content
 首页 » 编程设计

Python,Django,在类内部使用 Import,似乎无法解决这个问题

2025年05月04日22yxwkf

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

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”的类属性/方法不同

请您参考如下方法:

这对我来说很好。

但是你最好这样做:

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

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

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

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