简体   繁体   中英

python variable scope issue

i am stuck at scope resolution in python. let me explain a code first:

class serv_db:
def __init__(self, db):
    self.db = db 
    self.dbc = self.db.cursor()

def menudisp (self):
    print"Welcome to Tata Motors"
    print"Please select one of the options to continue:"
    print"1. Insert Car Info"
    print"2. Display Car Info"
    print"3. Update Car Info"
    print"4. Exit"
    menu_choice = raw_input("Enter what you want to do: ")
    if menu_choice==1: additem()
    elif menu_choice==2: getitem()
    elif menu_choice==3: edititem()
    elif menu_choice==4: sys.exit()

def additem (self):
    reg = raw_input("\n\nTo continue, please enter the Registration # of car: ") 
    print"There are 3 books in our database:"
    print"1. Job Card"
    print"2. Car"
    print"3. Customer"
    ch = raw_input("\nEnter your choice: ")
    if ch==1: adnewjob()
    elif ch==2: adnewcar(self, reg)
    elif ch==3: adnewcust()

def adnewcar ( self, reg ):
print "adding info to database: car"
    carreg = reg  #error here
    mftr = raw_input("Enter the Manufacturer of your car: ")
    model = raw_input("Enter the Model of your car: ")
    car_tb = (carreg,mftr,model)
    #writing to DB
    self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb)

def main():
        db = MySQLdb.connect(user="root", passwd="", db="tatamotors")
        service = serv_db(db)
        service.menudisp()

if __name__ == '__main__':
     main() 

i am inputting a registration num into the variable reg now based upon the user's choice one of three functions is performed. i havent yet created the adnewjob() and adnewcust() functions yet. the adnewcar() is ready. when i try to pass the value down to the adnewcar() function, it gives an error saying:

This is the entire traceback:

Traceback <most recent call last>:
  File "tatamotors.py", line 5, in <module>
    class serv_db:
  File "tatamotors.py", line 38, in serv_db
    carreg = reg
Name Error: name 'reg' is not defined

i am pretty sure i am making some mistake. n00b here. go easy. thanks :)

EDIT i have joined all the relevant functions and classes. i have also included the related functions too.

It's a mistake to explicitly pass self when calling a method on your class. It's another mistake comparing ch to integers, when raw_input returns a string

Try

elif ch=='2': self.adnewcar(reg)

instead

You also have a print misindented in adnewcar.

But even then, after fixing all this I cannot reproduce your NameError. You really need to edit your question with

  • More code (the whole class at least.)
  • Full traceback of the error.

EDIT: I really don't know how you even get that traceback. The code you pasted is filled with the errors I illustrate, no use of self and no use of quotes around the integer.

Per chance are you using Python 3.0? What's your environment?

For the record, this works for me, using Python 2.5.2

class serv_db:
        def __init__(self, db):
                self.db = db
                self.dbc = self.db.cursor()

        def menudisp (self):
                print"Welcome to Tata Motors"
                print"Please select one of the options to continue:"
                print"1. Insert Car Info"
                print"2. Display Car Info"
                print"3. Update Car Info"
                print"4. Exit"
                menu_choice = raw_input("Enter what you want to do: ")
                if menu_choice=='1': self.additem()
                elif menu_choice=='2': self.getitem()
                elif menu_choice=='3': self.edititem()
                elif menu_choice=='4': sys.exit()

        def additem (self):
                reg = raw_input("\n\nTo continue, please enter the Registration # of car: ")
                print"There are 3 books in our database:"
                print"1. Job Card"
                print"2. Car"
                print"3. Customer"
                ch = raw_input("\nEnter your choice: ")
                if ch=='1': self.adnewjob()
                elif ch=='2': self.adnewcar(reg)
                elif ch=='3': self.adnewcust()

        def adnewcar ( self, reg ):
            print "adding info to database: car"
            carreg = reg  #error here
            mftr = raw_input("Enter the Manufacturer of your car: ")
            model = raw_input("Enter the Model of your car: ")
            car_tb = (carreg,mftr,model)
            #writing to DB
            self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb)

def main():
        db = MySQLdb.connect(user="root", passwd="", db="tatamotors")
        service = serv_db(db)
        service.menudisp()

if __name__ == '__main__':
     main()

You need all these three:

if menu_choice==1: self.additem() # 1: self.
elif ch=='2': self.adnewcar(reg) # 2: self. instead of (self, reg)
    print "adding info to database: car"  # 3: indented.

Always remember to keep indents consistent throughout a .py, otherwise the interpreter will have a hard time keeping track of your scopes.

is it a copy error or do you have your indentation wrong? The (I suppose) methods align with the class definition instead of being indented one level.

Perhaps you are mixing tabs and spaces?

btw if you define your class correctly you should be calling self.additem() instead of additem() (and the same goes for adnewcar(self,reg , at the moment it works because it is in fact not a method, but a module level function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM