为模块导入和使用传递变量
Passing variable for module import and use
所以我正在尝试使用由用户 select 编辑的可变品牌。然后该变量将用于调用 Python 中的给定模块。目前在第 7 行你可以看到 'apple.solutions()'。但是,我基本上希望能够在 'brand.solutions()' 行中使用某些东西——尽管我知道这不会起作用,因为它需要该属性。我正在寻找 select 基于可变品牌的模块的解决方案。我将不胜感激任何解决方案或建议。谢谢,
主程序:
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
您可能正在寻找对 Main() 函数的调用:
if __name__ == "__main__":
Main()
上面的代码应该放在主程序的末尾。它检查主程序是否被导入,然后执行Main()
函数,如果它没有被导入并作为独立程序运行。
#!/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
函数动态导入模型
所以我正在尝试使用由用户 select 编辑的可变品牌。然后该变量将用于调用 Python 中的给定模块。目前在第 7 行你可以看到 'apple.solutions()'。但是,我基本上希望能够在 'brand.solutions()' 行中使用某些东西——尽管我知道这不会起作用,因为它需要该属性。我正在寻找 select 基于可变品牌的模块的解决方案。我将不胜感激任何解决方案或建议。谢谢,
主程序:
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
您可能正在寻找对 Main() 函数的调用:
if __name__ == "__main__":
Main()
上面的代码应该放在主程序的末尾。它检查主程序是否被导入,然后执行Main()
函数,如果它没有被导入并作为独立程序运行。
#!/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
函数动态导入模型