scope - How to access private variable of Python module from class -
in python 3, prefixing class variable makes private mangling name within class. how access module variable within class?
for example, following 2 ways not work:
__a = 3 class b: def __init__(self): self.a = __a b = b() results in:
traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 3, in __init__ nameerror: name '_b__a' not defined using global not either:
__a = 3 class b: def __init__(self): global __a self.a = __a b = b() results in:
traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 4, in __init__ nameerror: name '_b__a' not defined running locals() shows variable __a exists unmangled:
>>> locals() {'__package__': none, '__name__': '__main__', '__loader__': <class '_frozen_importlib.builtinimporter'>, '__doc__': none, '__a': 3, 'b': <class '__main__.b'>, '__builtins__': <module 'builtins' (built-in)>, '__spec__': none} [newlines added legibility]
running same code in module (as opposed interpreter) results in exact same behavior. using anaconda's python 3.5.1 :: continuum analytics, inc..
it's ugly access globals:
__a = 3 class b: def __init__(self): self.a = globals()["__a"] b = b() you can put in dict:
__a = 3 d = {"__a": __a} class b: def __init__(self): self.a = d["__a"] b = b() or list, tuple etc.. , index:
__a = 3 l = [__a] class b: def __init__(self): self.a = l[0] b = b()
Comments
Post a Comment