簡體   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