首页 > 解决方案 > 如何在 Python 的类中更改全局变量的值?

问题描述

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

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"

标签: pythonclassvariablesglobal-variables

解决方案


您应该声明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

推荐阅读