0

As below codes showed, I defined a global variable first, then I want to use it in a class, but failed.

__var = 10

def test01():
    return __var

r1 = test01()
# 10


class Test:
    def test02(self):
        return __var

r2 = Test().test02()
# NameError: name '_Test__var' is not defined

Isn't __var a global variable? why I get error in second demo?


_Test__var = 10

class Test:
    def test02(self):
        return __var

r2 = Test().test02()
# 10 worked as I defined `_Test__var = 10` as error showed
jia Jimmy
  • 1,693
  • 2
  • 18
  • 38
  • 1
    not sure why, but the problem does not occur if you remove the two underscores, or even one of them – olinox14 Sep 09 '19 at 09:28
  • 1
    Double underscore means the variable is "private". In quotation marks, because in Python nothing is really private, it's just access gets reaaally complicated. I don't know how to access such module-level (file-level aka global) variables, but for classes it works like your error shows (if you want to use it outside the class, you use `_ClassNameHere__variable`). – h4z3 Sep 09 '19 at 09:32
  • 1
    And it shows that error because obviously it doesn't see `__var` normally because of those protections. So it assumes it's something within that class (hence it seeks `_Test__var`), but it doesn't exist anyway, so it throws the error. – h4z3 Sep 09 '19 at 09:34
  • 1
    The issue here is that when you try access `__var` inside `Test`, you are trying to access mangled variable name. Variables with two `__` are being mangled (it's a sort of `privacy` by mangling). You can still access global variable with: `globals()['__var']` – Oo.oO Sep 09 '19 at 09:38

0 Answers0