简体   繁体   English

python变量范围问题

[英]python variable scope issue

i am stuck at scope resolution in python. 我被困在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. 我现在根据用户的选择将注册编号输入到变量reg ,这是三个功能之一。 i havent yet created the adnewjob() and adnewcust() functions yet. 我还没有创建adnewjob()adnewcust()函数。 the adnewcar() is ready. adnewcar()已准备就绪。 when i try to pass the value down to the adnewcar() function, it gives an error saying: 当我尝试将值传递给adnewcar()函数时,出现错误提示:

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. n00b在这里。 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. 在类上调用方法时显式传递self是一个错误。 It's another mistake comparing ch to integers, when raw_input returns a string 当raw_input返回一个字符串时,将ch与整数进行比较是另一个错误

Try 尝试

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

instead 代替

You also have a print misindented in adnewcar. 您还可能在adnewcar中出现了打印错误。

But even then, after fixing all this I cannot reproduce your NameError. 但是即使如此,修复所有这些之后,我仍无法重现您的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. 您粘贴的代码充满了我说明的错误,没有使用self,也没有使用整数周围的引号。

Per chance are you using Python 3.0? 您是否有机会使用Python 3.0? What's your environment? 您的环境如何?

For the record, this works for me, using Python 2.5.2 记录下来,使用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. 始终记得在整个.py文件中保持缩进一致,否则解释器将很难跟踪您的范围。

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. 顺便说一句,如果您正确定义了类,则应该调用self.additem()而不是additem() (并且adnewcar(self,reg)仍然有效,因为它实际上不是方法,而是模块级别功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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