2015-08-22 39 views
0

我正在嘗試構建一個簡單的計算器,但我收到了ImportError: cannot import name verify_sessionImportError:無法導入名稱verify_session

我想這是某種循環導入,但我不知道如何解決這些類型的錯誤。

文件夾結構

/calculator 
/--app.py 
/--decorators.py 

app.py

from decorators import verify_session 


class InvalidAmountException(Exception): 
    pass 


class InvalidSessionException(Exception): 
    pass 


class Calculator(object): 
    def __init__(self): 
     self.amount = 150 
     self.password = 'randompass123' 
     self.session = False 

    def __check_balance(self, amount): 
     if self.amount - amount < 0: 
      raise InvalidAmountException 
     return True 

    def kill(self): 
     self.session = False 
     return self.session 

    @verify_session 
    def withdrawal(self, amount): 
     try: 
      self.__check_balance(amount) 
      self.amount -= amount 
     except InvalidAmountException: 
      print 'Sum amount not avaliable!' 

    def deposit(self, amount): 
     self.amount += amount 

    def get_amount(self): 
     return self.amount 


if __name__ == '__main__': 
    m = Calculator() 
    m.deposit(150) 
    m.withdrawal(21) 
    m.withdrawal(2451) 

decorators.py

from app import InvalidSessionException 

def verify_session(func): 
    def func_wrapper(self, *args, **kwargs): 
     if not self.session: 
      raise InvalidSessionException 

    return func_wrapper 

回答

2

你是正確的,你是看到app.py和decorators.py之間的循環依賴關係。

我建議將例外從app.py移入它們自己的文件,例如myExceptions.py並將它們導入到app.py和decorators.py中。

myExceptions.py

class InvalidAmountException(Exception): 
    pass 

class InvalidSessionException(Exception): 
    pass 

app.py

from decorators import verify_session 

from myExceptions import InvalidAmountException, InvalidSessionException 

... 

decorators.py

from myExceptions import InvalidSessionException 

... 
+0

這是我第一次,但它仍然沒有奏效。在這種情況下,我會在'decorators.py'中得到'ImportError:無法導入名稱InvalidSessionException' – intelis

+0

我會用一個可能會清除的簡短示例更新我的答案,併爲您的例外文件建議一個不同的名稱,以避免任何潛在的命名空間與內建異常類的衝突。 – Erik

+0

你是對的。名字是問題。一旦我改變了它,一切正常 – intelis

1

@Erik suggestio n正在工作。我創建了文件myExceptions.py 並在那裏移動了自定義異常類。請檢查下面的代碼:

#myexceptions.py 

class InvalidAmountException(Exception): 
    pass 


class InvalidSessionException(Exception): 
    pass 

#Modified a code bit in decorators.py 

from myexceptions import InvalidSessionException 

def verify_session(func): 
    def func_wrapper(self, *args, **kwargs): 
     try: 
      if not self.session: 
      raise InvalidSessionException 
     except InvalidSessionException: 
     print "Invalid session. Logging off..." 
    return func_wrapper 

#When I executed app.py my output is looking like this... 

E:\calc>python app.py 
Invalid session. Logging off... 
Invalid session. Logging off... 

E:\calc> 
相關問題