python - 如何在 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"
解决方案
您应该声明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
推荐阅读
- reactjs - react-navigation 用反应上下文包装根 AppContainer
- javascript - 为什么我得到未定义的变量?
- c# - 提交表单后 ASP.net MVC ViewModel 属性为空
- javascript - 如何使用javascript动态获取选中复选框的值
- c# - X509Certificate2UI.SelectFromCollection 正在关闭应用程序
- angular - Angular 7 类继承和 httpClient
- svn - Ansible SVN 结帐中的“无法在路径中找到所需的可执行 svn”错误
- html - 为什么 href="/../subpage/doc.html" 有效?
- r - 仅在满足条件时才起作用的默认参数
- google-cloud-platform - GCloud Storage:如何授予在控制台中查看存储桶的权限,但只能查看单个存储桶中的文件?