Python-如何从其他文件导入函数中的变量?

时间:2019-10-05 07:23:40

标签: python-3.x python-import importerror

我想知道的是如何将变量-元素传递到第二个文件中?这样我就可以将此元素用作函数中的参数,也可以用作值,以稍后定义数组中变量的位置。

此外,变量-元素在文件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'放在loggingInMenu()中,它将说出“ unresolved reference'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)

1 个答案:

答案 0 :(得分:0)

将值从一个文件(模块)传递到另一个文件。

为解决您的将变量从一个模块传递到另一个模块的问题,我采用了class的方法,您要file2访问的变量(element)是< file1的em>属性。

设置:

  • 两个文件都放置在同一目录中,该目录包含一个__init__.py文件。
  • 实例化时,file2创建一个file1的实例,该实例运行您的登录脚本,并将element属性存储到file2的类属性中。
  • 接下来,将调用菜单,并使用在self._element中创建的file1属性。

这是代码,说实话,比描述的简单得多。

清理编辑:

此外,(如果愿意,请丢弃它们)我对原始代码进行了几次PEP / Pythonic编辑:

  • if语句更改为使用all()函数,该函数测试列表中的所有条件均为True
  • 更新后的代码使用纯小写字母-除了类(驼峰类)之外。
  • 将您的if existAccount == False:语句更新为更具Python风格的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.