How to Access Static Class Variables Within Methods in Python?

Mary-Kate Olsen
Release: 2024-10-27 14:27:30
Original
448 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Create static class variable: Foo.bar

    <code class="python">def bah(self):
         print(Foo.bar)</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!