开发者

LGB Scoping Rule and Using "self" in Python

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 namesp开发者_运维百科ace of instance g is the first namespace where str2 can be found! So, the result should be "Instance".

Is this wrong?


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.


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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜