Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help needed classes and functions!!! Getting values

Status
Not open for further replies.

abc73

Programmer
Apr 28, 2004
89
US
hi,
I have a small problem I think the following code explains what I am trying to do:
*****************************************
class TEST:
def __init__ (self):
print "INSTANCE"
def A (self):
self.a = 'AZ'
def B (self):
print self.a

if __name__ == '__main__':

test = TEST()
test.B()
******************************************
I am trying to get the value of self.a in def B() though it is being declared in def A(). Currently it doesn't work and gets an error:
AttributeError: Azeem instance has no attribute 'a'

Now is there a way to get the value of self.a in def B() without declaring self.a in __init__() i.e. any way to get to that value using any class reference or anything.

What I want to do is that create multiple lists at runtime in different methods. I am not sure ahead how many lists I need to create as it all depends on the data in the input-file. I have different methods that populate the relevant lists. That's a small picture of the code I am working. Any help is appreciated.
Thanks
 
Well, right now you have a scope issue. Since a is first used in def A it is created with scope only in that def. Once the def exits/completes it is thrown out.
The easy answer would be to define a in a higher level, like so:
Code:
class TEST:
    a = ''
    def __init__ (self):
        print "INSTANCE"
    def A (self):
        self.a = 'AZ'
    def B (self):
        print self.a
        
if __name__ == '__main__':

    test = TEST()
    test.B()
(pardon my syntax if incorrect, been working in to many languages recently).

Now since your going to have an unknown number of lists, defining a like that won't help because you may need several list references. Best bet would probably be to create a list of lists at that higher level. That way each time you need to add another list you could just add the created list to the master list that has class wide access. So you would define something (maybe call it masterList) where a is defined. Then each list you read and create from the data files you would add to that master list. Accessing them would be a simple matter of either looping through the master list or pulling out one of the lists from the master list by index.

-T

01000111 01101111 01110100 00100000 01000011 01101111 01100110 01100110 01100101 01100101 00111111
The never-completed website:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top