我在python文件中声明了几个全局变量,并希望在函数中将它们的值重置为None。是否有更好的/hack/pythonic方法将所有变量声明为全局变量,并在一行中为它们赋值?
doctype, content_type, framework, cms, server = (None,)*5
def reset():
doctype, content_type, framework, cms, server = (None,)*5发布于 2014-02-26 08:55:00
使用globals获取对全局变量的dict的引用:
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
>>> globals().update({'a': 2})
>>> a
2
>>> 就你而言:
globals().update({
'doctype': None,
'content_type': None,
...
})用一条线理解来做这件事:
或者这个:
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
globals()[var_name] = None或者这个:
module = sys.modules[__name__]
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
setattr(var_name, None)发布于 2014-02-26 08:52:34
Chain =,因为您将不可变的None与它们联系在一起:
doctype = content_type = framework = cms = server = None如果要使用reset函数,则必须在其中声明为global:
def reset():
global doctype, content_type, framework, cms, server
doctype = content_type = framework = cms = server = None发布于 2014-02-26 09:05:58
在本例中,我将使用一个全局可变对象,例如dict:
conf = dict.fromkeys(['doctype', 'content_type', 'framework', 'cms', 'server'])
def reset():
for k in conf:
conf[k] = None或者上课。通过这种方式,您可以在类本身中封装reset:
class Config():
doctype = None
content_type = None
framework = None
cms = None
server = None
@classmethod
def reset(cls):
for attr in [i for i in cls.__dict__.keys()
if i[:1] != '_' and not hasattr(getattr(cls, i), '__call__')]:
setattr(cls, attr, None)https://stackoverflow.com/questions/22036124
复制相似问题