简体   繁体   中英

Python, Django, using Import from inside of a class, can't seem to figure this out

I want to use imports inside a class that is then inherited by another class so that I don't have to manually define my imports in each file. I am trying it like this but its not working, any advice is appreciated:

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

I have tried variations of trying to use "self" but can't figure out how to appropriately use this with the import from as its not the same as a class attribute / method where I normally use 'self'

This works fine for me.

But you're better off doing this:

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

Note that doing it your way, you have to initialize them on a per instance basis and assign to self, like so:

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

either way, you can now access bar in other methods on that class or a derived one as self.bar .

In Python, an import just adds to current namespace. The namespace is lost once you return from the function, but you can preserve the pointer appending it to 'self'.

You can do:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM