Posted: 5/28/2015 1:56:07 PM EDT
|
im getting "NameError: global name 'fwddb' is not defined"
I have a class with 2 objects and im defining a list of tuples in the first function (it the __init__ function) and I need to access the data in the 2nd function defined in the class. how do I do this w/o making it global? |
|
Generally, you can help your future self by avoiding globals and keeping data around only as long and where you need it. This is called proper scoping, and it's key to being able to go back and intuitively understand code, as well as prevent several classes of errors.
Don't know what the 2 objects pertains to (two instances of a single class?), let me know if there's a crucial part I'm missing. Anyway, what you are probably looking for is class member variables, sometimes called class attributes or class fields. Here's an example. Look at this code, and once you think you got the gist of it down, try running it.
The key part about this is that the "self" attributes of a class can be referenced anywhere in the member functions of that object of the class, and they will only see the values for that particular object. So self.name on the fido object will be 'fido', but we could give another value to another Dog object, and when its lookAtTag() function was called it would see a different value for self.name. |