2011-04-21 5 views
0

매개 변수로 모듈을 받고 있는데 로컬 변수를 모두 가져 오려고합니다 (XXX 또는 함수 또는 클래스와 관련이 없음).
어떻게 할 수 있습니까?다른 모듈의 모든 로컬 변수를 검색하는 방법은 무엇입니까?

def _get_settings(self, module): 
     return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')] 

을하지만 제기 :

은 내가 시도

Traceback (most recent call last): 
    File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 1133, in <module> 
    debugger.run(setup['file'], None, None) 
    File "/home/omer/Aptana Studio 3/plugins/org.python.pydev.debug_1.6.5.2011012519/pysrc/pydevd.py", line 918, in run 
    execfile(file, globals, locals) #execute the script 
    File "/root/Aptana Studio 3 Workspace/website/website/manage.py", line 11, in <module> 
    import settings 
    File "/root/Aptana Studio 3 Workspace/website/website/settings.py", line 7, in <module> 
    settings_loader = Loader(localsettings) 
    File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 6, in __init__ 
    self.load(environment) 
    File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 9, in load 
    for setting in self._get_settings(module): 
    File "/root/Aptana Studio 3 Workspace/website/website/envconf/loader.py", line 16, in _get_settings 
    return [setting for setting in dir(module) if not inspect.ismodule(setting) and not inspect.isbuiltin(setting) and not inspect.isfunction(setting) and not setting.__NAME__.startswith('__')] 
AttributeError: 'str' object has no attribute '__NAME__' 
+1

당신은 아마'__name__'가 아닌'__NAME__'을 의미했다. 파이썬은 대소 문자를 구분합니다. – geoffspear

답변

2

dir()을 사용하여 모든 로컬 변수에 액세스 할 수 있습니다. 그러면 문자열 목록이 반환되며 각 문자열은 특성의 이름입니다. 이렇게하면 모든 변수와 메소드가 반환됩니다. 그냥 인스턴스 변수 위해 특별히 찾고 있다면, 이들은 예를 들어 __dict__를 통해 액세스 할 수 있습니다

>>> class Foo(object): 
...  def __init__(self, a, b, c): 
>>> 
>>> f = Foo(1,2,3) 
>>> f.__dict__ 
{'a': 1, 'c': 3, 'b': 2} 
>>> dir(f) 
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c'] 
2

dir() 문자열 목록을 반환합니다. setting.startswith()을 직접 사용하십시오.

관련 문제