【问题标题】:Passing variable for module import and use为模块导入和使用传递变量
【发布时间】:2016-12-28 10:41:18
【问题描述】:

所以我尝试使用用户选择的可变品牌。然后该变量将用于调用 Python 中的给定模块。目前在第 7 行,您可以看到“apple.solutions()”。但是,我本质上希望能够在“brand.solutions()”行上使用一些东西——尽管我知道这不起作用,因为它需要属性。我正在寻找一种解决方案来根据可变品牌选择模块。我将不胜感激任何解决方案或建议。谢谢,

主程序:

import apple, android, windows

brands = ["apple", "android", "windows"]
brand = None

def Main():
    query = input("Enter your query: ").lower()
    brand = selector(brands, query, "brand", "brands")
    solutions = apple.solutions()
    print(solutions)

Apple.py 模块文件(与主程序同目录):

def solutions():
    solutions = ["screen", "battery", "speaker"]
    return solutions

【问题讨论】:

    标签: python arrays variables parameter-passing python-module


    【解决方案1】:

    您可能正在寻找对 Main() 函数的调用:

    if __name__ == "__main__":
         Main()
    

    上面的代码应该放在主程序的末尾。它检查主程序是否被导入,如果没有导入则执行Main()函数并作为独立程序运行。

    【讨论】:

      【解决方案2】:
      #!/usr/bin/env python3
      # -*- coding: utf-8 -*-
      
      import apple, android, windows
      
      brands = ["apple", "android", "windows"] 
      
      def selector(brands, query):   
          if query in brands:
              exec("import %s as brand" % query)
          else:
              brand = None
      
          return brand
      
      
      def Main():
          query = raw_input("Enter your query: ").lower()
          brand = selector(brands, query) 
          solutions = brand.solutions()   
          print(solutions)
      
      
      if __name__ == '__main__':
          Main()
      

      我有一个简单的方法,就是使用exec函数来动态导入模型

      【讨论】:

      • 您好,感谢您的建议!我目前有一个处理错误处理方面的选择器函数,是否可以使用预定的品牌变量来实现 exec 函数?当前代码:pastebin.com/c876C3Qn 谢谢山姆
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2014-07-01
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      相关资源
      最近更新 更多