Передача значения из одного файла (модуля) в другой.
Чтобы ответить на ваш вопрос о передаче переменной из одного модуля в другой, я выбрал подход class
, где переменная, которую вы хотите file2
для доступа (element
) - это свойство из file1
.
Настройка:
- Оба файла размещены в одном каталоге,который содержит файл
__init__.py
. - При создании экземпляра
file2
создает экземпляр file1
, который запускает ваш скрипт входа в систему, и сохраняет свойство element
в атрибуте класса file2
. - Далее,меню вызывается и использует атрибут
self._element
, который был создан в file1
.
Вот код, и он, честно говоря, намного проще, чем кажется в описании.
Редактирование очистки:
Кроме того, (откажитесь от них, если хотите) Я внес пару изменений PEP / Pythonic в ваш исходный код:
- Изменено
if
оператор для использования функции all()
, которая проверяет для всех условий в списке значение True
. - Обновлен код для использования чистого нижнего регистра - за исключением класса, который является верблюдом.
- Обновлен ваш оператор
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.