How to Access Class Variables from Methods in Python?

DDD
Release: 2024-10-26 17:24:02
Original
949 people have browsed it

How to Access Class Variables from Methods in Python?

Accessing Class Variables in Methods

When working with classes in Python, you may encounter instances where you need to access class variables from within methods. However, simply referencing the variable within the method may result in a NameError.

The Issue

Consider the following code snippet:

<code class="python">class Foo(object):
    bar = 1

    def bah(self):
        print(bar)</code>
Copy after login

When attempting to run this code, you will encounter a NameError: global name 'bar' is not defined. This is because the variable bar is a class variable, and the method bah is not able to access it directly.

The Solution

To access class variables within methods, there are two options:

  • self.bar: This references the instance variable, which is specific to each instance of the class.
  • Foo.bar: This references the class variable, which is shared among all instances of the class.

If you intend to modify the class variable, use Foo.bar; otherwise, use self.bar.

Example

Refactoring the code snippet using the correct approach:

<code class="python">class Foo(object):
    bar = 1

    def bah(self):
        print(self.bar)  # Access the instance variable

f = Foo()
f.bah()  # Prints 1</code>
Copy after login

This code will print 1, accessing the instance variable. If you wish to access the class variable, simply change self.bar to Foo.bar in the print statement.

The above is the detailed content of How to Access Class Variables from 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
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!