Home  >  Article  >  Backend Development  >  How to Access Static Class Variables Within Methods in Python?

How to Access Static Class Variables Within Methods in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 14:27:30447browse

How to Access Static Class Variables Within Methods in Python?

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:

  1. Access static class variable: self.bar

    <code class="python"> def bah(self):
         print(self.bar)</code>
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn