Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 52
    As a caveat to Global access - reading a global variable can happen without explicit declaration, but writing to it without declaring global(var_name) will instead create a new local instance. Commented Jun 27, 2012 at 5:53
  • 13
    Actually @Peter, global(var_name) is syntactically incorrect. The correct syntax would be global var_name without parentheses. You have a valid point though. Commented Dec 24, 2012 at 21:48
  • If so, then why isn't foo's "y" variable visible to "bar" below: >>> def foo(x): ... y = x ... def bar(z): ... y = z ... bar(5) ... print x,y ... >>> foo(3) 3 3 Commented Feb 11, 2013 at 21:56
  • 3
    @Jonathan: Because each y is being written to and there are no global y declarations -- see @Peter's comment. Commented Aug 6, 2013 at 19:19
  • 1
    @Ctrl-C Not really; there is nothing special about class attributes in terms of scope. They are shared in the sense that self.someClassAttribute will refer to the same object regardless of which instance self refers to, but the name itself does have to be used as an attribute on an instance or the class itself. The actual special behavior is that while evaluating the statements in the class body, the class attribute will shadow any variables existing in the containing scope. E.g. j = 0; class Foo: j = 3; print(j); # end of class; print(j) will output 3, then 0. Commented Mar 1, 2019 at 15:28