Accessing Static Class Variables Within Methods
When attempting to access class variables within methods, an error can occur due to namespace differences. The code snippet below illustrates this issue:
<code class="python">class Foo(object): bar = 1 def bah(self): print(bar) # NameError: global name 'bar' is not defined</code>
Solution
To access static class variables within methods, utilize self.bar or Foo.bar. Foo.bar creates a static variable, while self.bar creates an instance variable. Thus, the following revisions resolve the issue:
Access static class variable: self.bar
<code class="python"> def bah(self): print(self.bar)</code>
Create static class variable: Foo.bar
<code class="python">def bah(self): print(Foo.bar)</code>
The above is the detailed content of How to Access Static Class Variables Within Methods in Python?. For more information, please follow other related articles on the PHP Chinese website!