Thread: Problem

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

    Join Date
    May 2013
    Rep Power

    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):
    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
    Rep Power
    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 you put the definition of the class) and (where the test will be done), here is how I will proceed:
    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)
    python Code:
    from Room import Room
    def main():
        test = []
        for newGuest in range(4):
        for indx in range (len(test)):
            print('{0} is registered as guest {1}'.

    Which gives you the desired output

    $ python -tt
    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.

IMN logo majestic logo threadwatch logo seochat tools logo