Thread: Problem

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    help: cant use variable outside class for inside an object.


    im learning python language atm and i got the following problem.

    class room:

    guest = None
    guestnumber = None

    def guest(self):
    self.guest = input()
    def guestnumber(self):
    self.guestnumber = (i+1)


    test = []
    for i in range(4):
    test.append(room())
    test[i].guest()
    test[i].guestnumber()
    for x in range (len(test)):
    print('{0} is registered as guest {1}'.format((test[x].guest),(test[x].guestnumber)))


    if i put this all in one page this script works for me. but when i put the class in a other .py file and i import the class to the rest of the code, i get an error because the i from the for loop is not defined in the class. how can i use that i variable in the class?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    149
    Rep Power
    140
    Obviously, the scope is different in terms of the variables when the code is separated in two files. Assuming that there are two files in the current working directory named respectively Room.py(where you put the definition of the class) and myscript.py (where the test will be done), here is how I will proceed:

    Room.py
    python Code:
     
    class Room:
        numberOfGuests = 0
     
        def __init__(self):
            self.__guestName = raw_input("Enter the guest name: ")
            Room.numberOfGuests += 1
            self.__guestNumber = Room.numberOfGuests
     
        def getGuestNumber(self):
            return self.__guestNumber
     
        def getGuestName(self):
            return self.__guestName

    and for the test script (in the same directory)

    myscript.py
    python Code:
     
    from Room import Room
     
    def main():
        test = []
        for newGuest in range(4):
            test.append(Room())
     
        for indx in range (len(test)):
            print('{0} is registered as guest {1}'.
                format((test[indx].getGuestName()),
                       (test[indx].getGuestNumber())))
     
     
    main()



    Which gives you the desired output

    Code:
    $ python -tt myscript.py
    Enter the guest name: peter
    Enter the guest name: John
    Enter the guest name: Frank
    Enter the guest name: Michael
    peter is registered as guest 1
    John is registered as guest 2
    Frank is registered as guest 3
    Michael is registered as guest 4
    $
    Also use CODE tags when you post a code on the forum as it makes it easier for others to read, particularly when we're talking about python where indentations are important.
    Regards,
    Dariyoosh

IMN logo majestic logo threadwatch logo seochat tools logo