繁体   English   中英

python变量范围问题

[英]python variable scope issue

我被困在python的范围解析中。 让我先解释一个代码:

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() 

我现在根据用户的选择将注册编号输入到变量reg ,这是三个功能之一。 我还没有创建adnewjob()adnewcust()函数。 adnewcar()已准备就绪。 当我尝试将值传递给adnewcar()函数时,出现错误提示:

这是整个回溯:

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

我很确定我犯了一些错误。 n00b在这里。 放轻松。 谢谢 :)

编辑我已经加入了所有相关的功能和类。 我也包括了相关功能。

在类上调用方法时显式传递self是一个错误。 当raw_input返回一个字符串时,将ch与整数进行比较是另一个错误

尝试

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

代替

您还可能在adnewcar中出现了打印错误。

但是即使如此,修复所有这些之后,我仍无法重现您的NameError。 您确实需要使用

  • 更多代码(至少是整个类)
  • 错误的完整回溯。

编辑:我真的不知道你怎么得到那个回溯。 您粘贴的代码充满了我说明的错误,没有使用self,也没有使用整数周围的引号。

您是否有机会使用Python 3.0? 您的环境如何?

记录下来,使用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()

您需要所有这三个:

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.

始终记得在整个.py文件中保持缩进一致,否则解释器将很难跟踪您的范围。

是复制错误还是缩进错误? (我想)方法与类定义保持一致,而不是缩进一个级别。

也许您在混合制表符和空格?

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

暂无
暂无

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

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