【问题标题】:How to change the value of a global variable inside a class in Python?如何在 Python 的类中更改全局变量的值?
【发布时间】:2020-06-28 08:03:35
【问题描述】:

我想为全局变量分配一个新值,但它不起作用

email = " "
class A():
    def __init__(self):
        ---some code---
    def assign_email(self):
        email = "max@gmail.com"
class B()
    def __init__(self):
        print(email)            #this returns an empty string, not the updated value "max@gmail.com"

【问题讨论】:

  • 使用全局,即将email = "max@gmail.com"替换为global email = "max@gmail.com"。我认为它应该工作。我要补充一点:这不是构建代码的一种很好的方式,并且 global 的使用应该非常有限,因为理解电子邮件参数的价值来自哪里会令人困惑。
  • 考虑将email 设为类/实例变量,除非您真的知道自己在做什么并且必须拥有该全局变量。

标签: python class variables global-variables


【解决方案1】:

您应该声明email 是全局变量而不是本地变量。 你可以这样做:
global email

email = " "
class A():
    def __init__(self):
        pass
        # ---some code---
    def assign_email(self):
        global email # this makes email to be the global email
        email = "max@gmail.com"
class B():
    def __init__(self):
        print(email)            #this returns an empty string, not the updated value "max@gmail.com"
a = A()
a.assign_email()
b = B()
print(email) # global email

【讨论】:

  • 是的,这确实有效。但不知何故,在我的 python-kivy 代码中同样不起作用
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多