Warning

 

Close
Confirm Action

Are you sure you wish to do this?

Cancel Confirm
AR15.COM
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?
5/29/2015 11:26:58 PM EDT
[#1]
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.


#!/usr/bin/python3

class Dog:
   def __init__(self, name, home_address=None, has_id_tag=True):
       self.name=name
       self.home_address=home_address
       self.has_id_tag=has_id_tag

   def hasTag(self):
        return self.has_id_tag

   def lookAtTag(self):
        results = [self.name]
        if self.home_address != None:
            results.extend(self.home_address)
        return results
       
   @staticmethod
   def bark():
        print('"bark!"')

if __name__=='__main__':
   fido = Dog('fido', ('123 Fake St.', 'Houston, TX'))
   print('ok look, a dog!')
   fido.bark()
   if fido.hasTag():
       print('lets see what its collar says')
       [ print("\t"+x) for x in fido.lookAtTag() ]


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.