Python import a module into one class only
I am trying to get a module to import, but only if an object of a specific class is开发者_开发问答 called. For example:
class One(object):
try:
import OneHelper
except ImportError:
pass
def __init__(self):
# this function doesn't use OneHelper
...
def blah(self):
# this function does
OneHelper.blah()
This causes a NameError: global name 'OneHelper' is not defined
when the One.blah()
function is called. So far the only thing I have found that works is importing the module into the actual functions that use it. So:
class One(object):
def __init__(self):
# this function doesn't use OneHelper
...
def blah(self):
try:
import OneHelper
except ImportError:
pass
# this function does
OneHelper.blah()
But I don't want to have to import the module in each function I want to use it in, I want it to be available to the whole class, but only if an instance of that class is instantiated. Apologies if I'm not being clear enough...
The import OneHelper
works fine in the class, making it a class attribute. You can verify this with dir(One)
after defining your class -- there's your OneHelper
attribute. One.OneHelper
is a reference to the module. In an instance, of course, you may access it as self.OneHelper
from your methods. (You could also continue to access it as One.OneHelper
.)
Import it on __init__
and attribute to some property:
class One(object):
def __init__(self):
try:
import OneHelper
except ImportError:
self.OneHelper = None
else:
self.OneHelper = OneHelper
def blah(self):
if self.OneHelper:
self.OneHelper.blah()
Your example looks funny because if the module fails to import what is the point of calling it later?
You might also consider using global OneHelper
before importing the module. This adds the OneHelper to the global namespace.
精彩评论