Python - 如何从其他文件导入函数中的变量?
Python - How to import a variable in a function from other file?
我想知道如何将变量 - 元素传递到第二个文件中?这样我就可以将此元素用作函数中的参数,也可以用作稍后定义数组中变量位置的值。
此外,变量 - 元素的值应与文件 1 和文件 2 中的 'i' 相同。
文件 1:这是我程序的一部分。
def menu():
existAccount = False
element = 0
print("Welcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputEmail = input("Enter Email: ")
inputPassword = input("Enter Password: ")
for i in range(len(customers)):
if inputEmail == customers[i].getEmail() and inputPassword == customers[i].getPassword():
existAccount = True
element = i
break
if existAccount == False:
print("Incorrect Email/Password")
menu()
loggedInMenu(int(element))
文件 2:
现在,如果我将 'element' 放入 loggedInMenu() ,它会显示 "unresolved reference 'element'"。如果我不这样做,它会说“参数 'element' 未填充”。
from STLPStoreMain import *
def AppMenu():
choose = input("Enter:")
if choose == '1':
#customers is a array which contain class objects. getEmail() is a method to access hidding information.
print ("Email:", customers[element].getEmail())
print("Password: " + "*" * len(customers[element].getPassword()))
print ("Bill Address", customers[element].getBillAdd())
print ("Credit Card Number:", customers[element].getCredNum())
AppMenu()
if choose == '6':
loggedInMenu(element)
将值从一个文件(模块)传递到另一个文件(模块)。
为了解决您将变量从一个模块传递到另一个模块的问题,我采用了 class
方法,您希望 file2
访问的变量 (element
) 是属性,共 file1
。
设置:
- 两个文件都放在同一个目录下,其中包含一个
__init__.py
文件。
- 在实例化时,
file2
创建一个 file1
的实例,它运行您的登录脚本,并将 element
属性 存储到 class 属性中file2
.
- 接下来,调用菜单,并使用在
file1
中创建的 self._element
属性。
这是代码,老实说 比描述看起来简单。
清理编辑:
此外,(如果你愿意,请丢弃它们)我对你的原始代码进行了几次 PEP/Pythonic 编辑:
- 将
if
语句更改为使用 all()
函数,该函数测试列表中的所有条件是否为 True
。
- 更新代码以使用纯小写字母 - class 除外,它是驼峰式。
- 将您的
if existAccount == False:
语句更新为更 Pythonic if not existaccount:
。
file1.py
由于我无法接触到您的客户,因此添加了一个简单的 _customers
词典用于测试。扔掉它并取消注释访问您的 customers
对象的行。
class StartUp():
"""Prompt user for credentials and verify."""
def __init__(self):
"""Startup class initialiser."""
self._element = 0
self._customers = [{'email': 'a@a.com', 'password': 'a'},
{'email': 'b@b.com', 'password': 'b'},
{'email': 'c@c.com', 'password': 'c'},
{'email': 'd@d.com', 'password': 'd'}]
self.menu()
@property
def element(self):
"""The customer's index."""
return self._element
def menu(self):
"""Display main menu to user and prompt for credentials."""
existaccount = False
print("\nWelcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputemail = input("Enter Email: ")
inputpassword = input("Enter Password: ")
# for i in range(len(customers)):
# if all([inputemail == customers[i].getemail(),
# inputpassword == customers[i].getpassword()]):
for i in range(len(self._customers)):
if all([inputemail == self._customers[i]['email'],
inputpassword == self._customers[i]['password']]):
self._element = i
existaccount = True
break
if not existaccount:
print("incorrect email/password")
self._element = 0
self.menu()
file2.py
class AppMenu():
"""Provide a menu to the app."""
def __init__(self):
"""App menu class initialiser."""
# Display the startup menu and get element on class initialisation.
self._element = StartUp().element
self._customers = [{'email': 'a@a.com', 'password': 'a', 'addr':
'1A Bob\'s Road.', 'cc': '1234'},
{'email': 'b@b.com', 'password': 'b',
'addr': '1B Bob\'s Road.', 'cc': '5678'},
{'email': 'c@c.com', 'password': 'c',
'addr': '1C Bob\'s Road.', 'cc': '9123'},
{'email': 'd@d.com', 'password': 'd',
'addr': '1D Bob\'s Road.', 'cc': '4567'}]
self.menu()
def menu(self):
"""Provide an app menu."""
choose = input("Enter: ")
if choose == '1':
# customers is a array which contain class objects. getemail() is a method
# to access hidding information.
# print ("email:", customers[element].getemail())
# print("password: " + "*" * len(customers[element].getpassword()))
# print ("bill address", customers[element].getbilladd())
# print ("credit card number:", customers[element].getcrednum())
print('-'*25)
print ("email:", self._customers[self._element].get('email'))
print("password: " + "*" * len(self._customers[self._element].get('password')))
print ("bill address:", self._customers[self._element].get('addr'))
print ("credit card number:", self._customers[self._element].get('cc'))
print('-'*25)
self.menu()
if choose == '6':
# loggedinmenu(element)
print('Not implemented.')
输出:
# Create an instance of the menu and run login.
am = AppMenu()
Welcome to STLP Store!
1.Login
2.Sign Up
3.Exit
Enter(1-3): 1
Enter Email: b@b.com
Enter Password: b
Enter: 1
-------------------------
email: b@b.com
password: *
bill address: 1B Bob's Road.
credit card number: 5678
-------------------------
Enter: 6
Not implemented.
我想知道如何将变量 - 元素传递到第二个文件中?这样我就可以将此元素用作函数中的参数,也可以用作稍后定义数组中变量位置的值。
此外,变量 - 元素的值应与文件 1 和文件 2 中的 'i' 相同。
文件 1:这是我程序的一部分。
def menu():
existAccount = False
element = 0
print("Welcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputEmail = input("Enter Email: ")
inputPassword = input("Enter Password: ")
for i in range(len(customers)):
if inputEmail == customers[i].getEmail() and inputPassword == customers[i].getPassword():
existAccount = True
element = i
break
if existAccount == False:
print("Incorrect Email/Password")
menu()
loggedInMenu(int(element))
文件 2: 现在,如果我将 'element' 放入 loggedInMenu() ,它会显示 "unresolved reference 'element'"。如果我不这样做,它会说“参数 'element' 未填充”。
from STLPStoreMain import *
def AppMenu():
choose = input("Enter:")
if choose == '1':
#customers is a array which contain class objects. getEmail() is a method to access hidding information.
print ("Email:", customers[element].getEmail())
print("Password: " + "*" * len(customers[element].getPassword()))
print ("Bill Address", customers[element].getBillAdd())
print ("Credit Card Number:", customers[element].getCredNum())
AppMenu()
if choose == '6':
loggedInMenu(element)
将值从一个文件(模块)传递到另一个文件(模块)。
为了解决您将变量从一个模块传递到另一个模块的问题,我采用了 class
方法,您希望 file2
访问的变量 (element
) 是属性,共 file1
。
设置:
- 两个文件都放在同一个目录下,其中包含一个
__init__.py
文件。 - 在实例化时,
file2
创建一个file1
的实例,它运行您的登录脚本,并将element
属性 存储到 class 属性中file2
. - 接下来,调用菜单,并使用在
file1
中创建的self._element
属性。
这是代码,老实说 比描述看起来简单。
清理编辑:
此外,(如果你愿意,请丢弃它们)我对你的原始代码进行了几次 PEP/Pythonic 编辑:
- 将
if
语句更改为使用all()
函数,该函数测试列表中的所有条件是否为True
。 - 更新代码以使用纯小写字母 - class 除外,它是驼峰式。
- 将您的
if existAccount == False:
语句更新为更 Pythonicif not existaccount:
。
file1.py
由于我无法接触到您的客户,因此添加了一个简单的 _customers
词典用于测试。扔掉它并取消注释访问您的 customers
对象的行。
class StartUp():
"""Prompt user for credentials and verify."""
def __init__(self):
"""Startup class initialiser."""
self._element = 0
self._customers = [{'email': 'a@a.com', 'password': 'a'},
{'email': 'b@b.com', 'password': 'b'},
{'email': 'c@c.com', 'password': 'c'},
{'email': 'd@d.com', 'password': 'd'}]
self.menu()
@property
def element(self):
"""The customer's index."""
return self._element
def menu(self):
"""Display main menu to user and prompt for credentials."""
existaccount = False
print("\nWelcome to STLP Store!")
print("1.Login\n2.Sign Up\n3.Exit")
user = int(input("Enter(1-3): "))
if user == 1:
inputemail = input("Enter Email: ")
inputpassword = input("Enter Password: ")
# for i in range(len(customers)):
# if all([inputemail == customers[i].getemail(),
# inputpassword == customers[i].getpassword()]):
for i in range(len(self._customers)):
if all([inputemail == self._customers[i]['email'],
inputpassword == self._customers[i]['password']]):
self._element = i
existaccount = True
break
if not existaccount:
print("incorrect email/password")
self._element = 0
self.menu()
file2.py
class AppMenu():
"""Provide a menu to the app."""
def __init__(self):
"""App menu class initialiser."""
# Display the startup menu and get element on class initialisation.
self._element = StartUp().element
self._customers = [{'email': 'a@a.com', 'password': 'a', 'addr':
'1A Bob\'s Road.', 'cc': '1234'},
{'email': 'b@b.com', 'password': 'b',
'addr': '1B Bob\'s Road.', 'cc': '5678'},
{'email': 'c@c.com', 'password': 'c',
'addr': '1C Bob\'s Road.', 'cc': '9123'},
{'email': 'd@d.com', 'password': 'd',
'addr': '1D Bob\'s Road.', 'cc': '4567'}]
self.menu()
def menu(self):
"""Provide an app menu."""
choose = input("Enter: ")
if choose == '1':
# customers is a array which contain class objects. getemail() is a method
# to access hidding information.
# print ("email:", customers[element].getemail())
# print("password: " + "*" * len(customers[element].getpassword()))
# print ("bill address", customers[element].getbilladd())
# print ("credit card number:", customers[element].getcrednum())
print('-'*25)
print ("email:", self._customers[self._element].get('email'))
print("password: " + "*" * len(self._customers[self._element].get('password')))
print ("bill address:", self._customers[self._element].get('addr'))
print ("credit card number:", self._customers[self._element].get('cc'))
print('-'*25)
self.menu()
if choose == '6':
# loggedinmenu(element)
print('Not implemented.')
输出:
# Create an instance of the menu and run login.
am = AppMenu()
Welcome to STLP Store!
1.Login
2.Sign Up
3.Exit
Enter(1-3): 1
Enter Email: b@b.com
Enter Password: b
Enter: 1
-------------------------
email: b@b.com
password: *
bill address: 1B Bob's Road.
credit card number: 5678
-------------------------
Enter: 6
Not implemented.