1
str2 = "Global"

class InClass:
 str2 = "Class"
 def Set(self, msg):
  self.str2 = msg
 def Print(self):
  print(str2)

g = InClass()
g.Set("Instance")
g.Print()

If I run this code, I get "Global" as result. But I cannot understand why.

By calling Set() method of instance g, variable str2 is now in the namespace of instance g. Then, following LGB scoping rule, the namespace of instance g is the first namespace where str2 can be found! So, the result should be "Instance".

Is this wrong?

maplejune
  • 13
  • 3

3 Answers3

6

This isn't how this works. print(str2) from inside the method accesses the global str2. To access the str2 member, use print(self.str2).

Read this SO question and answers for the full details. An excerpt from there:

At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: the innermost scope, which is searched first, contains the local names; the namespaces of any enclosing functions, which are searched starting with the nearest enclosing scope; the middle scope, searched next, contains the current module's global names; and the outermost scope (searched last) is the namespace containing built-in names.

This doesn't include the class members, so you have to refer to them explicitly with self.

Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
2

self and self.__class__ are never implicitly searched during scope resolution in Python.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

because you have define str2 = "Global" that python interpreter takes default.i agree with Eli.if you want to print then you have to explicitly print(self.str2) for accessing class variable str2 = "Class"

print g.str2 (will give you Class as output)