-1
class Gui(): var = None def refreshStats(args): print(str(var)) clas = Gui() clas.refreshStats() 

Trace

File "sample.py", line 5, in refreshStats print(str(var)) NameError: name 'var' is not defined. 

Why?

3
  • 2
    You have made var a class attribute belonging to the Gui class, so you'd have to access it as Gui.var. Commented Apr 18, 2017 at 17:36
  • 1
    You're missing a self parameter on refreshStats, by the way (unless you intend args to be the class) Commented Apr 18, 2017 at 17:37
  • 1
    @cricket_007: nope, that would cause an error. technically the OP just renamed it... Commented Apr 18, 2017 at 17:38

3 Answers 3

1

If you want your variables to be visible within the scope of your class functions, pass self into every class function and use your class variables as self.var such as this:

class Gui(): var = None def refreshStats(self, args): print(str(self.var)) clas = Gui() clas.refreshStats() 

If you want to use this as an instance variable (only for this instance of the class) as opposed to a class variable (shared across all instances of the class) you should be declaring it in the __init__ function:

class Gui(): def __init__(self): self.var = None def refreshStats(self, args): print(str(self.var)) clas = Gui() clas.refreshStats() 
Sign up to request clarification or add additional context in comments.

4 Comments

And what if the class variable was intentional?
You also should be initializing your class variables in an init function. see edits
That's called an instance variable, not a class variable
Quite right, I hope my edits have clarified things
1

make method inside class either classmethod or instance method then you can access all class instance property or varable inside method if method is instance method or if class method then class property you can access inside method

class A(): a = 0 def aa(self): """instance method""" print self.a @classmethod def bb(cls): """class method""" print cls.a 

Comments

0

var is not defined in the scope of your refreshStats() function, as it is a class variable.

As such, if you want to access it, you can do Gui.var.

2 Comments

This is basically just rewording the error message without explaining why var is not defined.
@chepner hopefully more useful now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.