首页 > 解决方案 > 如何从_init_函数python中的用户输入函数调用变量?

问题描述

我有一个包含一些启动信息的初始化函数。我想

  1. 让用户输入他们的电子邮件地址,
  2. 将其保存到名为“user_id”的变量中
  3. 然后在init函数中使用该变量。

它似乎正在使用全局变量,但我读过使用全局变量是一个坏主意。

如何在不使用全局变量的情况下实现这一点?

user_id ="no email yet"

Class GetDatabase():

 def user_email_input():
    global user_id
    user_id = input("what is your email") 
    return


 def __init__(self,uri: Text = "localhost:2555", servername: Text = "schools") -> Text:
    global user_id

    self.uri = uri
    self.servername= servername
    self.me = user_id```
    

标签: python

解决方案


不好的方法,但如果你必须:

class GetDatabase:
    def __init__(self, uri="localhost:2555", servername="schools"):
        self.uri = uri
        self.servername = servername
        self.user_email_input()

    def user_email_input(self):
        self.me = input("what is your email: ")

将参数传递给类的实例化似乎正是您所需要的:

class GetDatabase:
    def __init__(self, user_id, uri="localhost:2555", servername="schools"):
        self.uri = uri
        self.servername = servername
        self.me = user_id

# then instantiated with
db = GetDatabase(my_user_id, my_uri, my_servername)

推荐阅读