是否存在替换全局变量或类变量的pythonic方法

时间:2018-05-13 09:14:36

标签: python-3.x global-variables

我使用类变量来替换避免使用全局变量,但我认为它不是pythonic方式,任何人都可以给我一个更好的方法吗?

类变量方式:

class A(object):
    _func_map=dynamic_load_from_module()
    _ad_map = dynamic_load_from_another_module()
    @classmethod
    def check_status(cls,host,port,user):
        #do something other
        return cls._func_map[user].verify()
    @classmethod
    def check_ad(cls,host,port,user):
        #do something other
        return cls._ad_map[user].check()

全局变量方式:

_global_func_map = dynamic_load_from_module()
_global_ad_map = dynamic_load_from_another_module()
def check_status(host,port,user):
    #do something other
    global _global_func_map 
    return _global_func_map[user].verify()
def check_ad(host,port,user):
    #do something other
    global _ad_map
    return _ad_map[user].check()

1 个答案:

答案 0 :(得分:1)

我想最pythonic的方式是一个模块:

#!/usr/env/bin/python
def dynamic_load_from_module(): pass
def dynamic_load_from_another_module(): pass

fun_map = dynamic_load_from_module()
ad_map = dynamic_load_from_another_module()

所以你像模块一样使用它:

from module import fun_map, ad_map
class Foo(object):

    @classmethod
    def check_ad(cls,host,port,user):
        return ad_map[user].check()

但是如果你需要在构造实例时调用它们,你可能想要做类似

的事情
#!/usr/env/bin/python
def dynamic_load_from_module(): pass
def dynamic_load_from_another_module(): pass

(所以你只需在模块中定义函数)

from module import dynamic_load_from_module, dynamic_load_from_another_module

class Foo(object):
    def __init__(self):
        self._fun_map = dynamic_load_from_module()
        self._ad_map = dynamic_load_from_another_module()

或者,如果您需要在构造实例时调用它们,但仍然是类'属性:

from module import dynamic_load_from_module, dynamic_load_from_another_module

class Foo(object):
    _fun_map = dynamic_load_from_module()
    _ad_map = dynamic_load_from_another_module()

还有很多其他方法(属性,类方法,静态方法等),但我非常确定该模块是最蟒蛇的。此外,它很容易设置,阅读和理解 - 所以为什么不呢。

相关问题