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>
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:
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>
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!