【问题标题】:Only Call a Function if another Function does not return None只有在另一个函数不返回 None 时才调用一个函数
【发布时间】:2018-05-13 20:18:17
【问题描述】:

所以我正在处理一项任务,该任务要求我处理两个单独的 python 文件,一个带有我的主要代码,另一个带有两个函数,一个用于加密文件,另一个用于解密文件。这是主代码文件的样子:

import sys

sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7')

from assgn7 import encrypt_file, decrypt_file

file_in = 'Sample.txt'
print('Encrypting input file', file_in)
enc_dict = encrypt_file(file_in)

print('-' * 20)

print('Decrypting input file', file_in)
decrypt_file(enc_dict, file_in + '.enc')

我应该修改此代码,以便仅当 encrypt_file() 不返回 None 时才调用 decrypt_file()

我该怎么办?我在考虑可能使用异常处理,但不知道这需要捕获什么样的错误。

【问题讨论】:

  • 至于使用异常,您需要知道decrypt_file 在这种情况下会引发什么异常。你可以看看它的文档,看看它的源代码,或者只试一次看看会发生什么——最后一个不太健壮,但我会这样做。

标签: python python-3.x function exception-handling


【解决方案1】:

只检查返回的对象

import sys

sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7')

from assgn7 import encrypt_file, decrypt_file

file_in = 'Sample.txt'
print('Encrypting input file', file_in)
enc_dict = encrypt_file(file_in)
if enc_dict is not None:
    print('-' * 20)
    print('Decrypting input file', file_in)
    decrypt_file(enc_dict, file_in + '.enc')

【讨论】:

    【解决方案2】:

    decrypt_file中,如果enc_dict为None,你可以终止函数。

    def decrypt_file(enc_dict, filein):
       if enc_dict is None:
          return 
       < rest of code >
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多