某些函数需要不被参数化的“常量”值(即不设计为以后重新定义)。虽然默认参数是 stored only once对于 each function , 有些只是作为参数没有多大意义(即成为 signature 的一部分)。对于(一个不是很有用的)例子:
def foo(bar):
my_map = {"rab": barType, "oof": fooType}
return my_map.get(bar,defaultType)()
为每次调用重新定义这样一个常量浪费了 CPU 时间和 RAM 空间。其他一些方法是将常量存储为模块级全局变量或使函数成为可调用类,但可能还有其他方法,也许吧?
当执行模块级全局方式时,我在我的(意思是作为一个)常量变量前加上“_”以表明它存在于不任何人的兴趣.我仍然觉得模块命名空间略有“污染”,更不用说shame of using了。东西as discouraged as globals完全:
_my_map = {"rab": barType, "oof": fooType}
def foo(bar):
return _my_map.get(bar,defaultType)()
或者将其转换为类。我将 __call__
设为 classmethod ,以避免创建实例的需要:
class foo:
my_map = {"rab": barType, "oof": fooType}
@classmethod
def __call__(cls,bar):
return cls.my_map.get(bar,defaultType)()
这些解决方案是否足够 pythonic?
还有其他方法吗?
作为一种习惯,使用这样的“常量”是否可以?
注意我示例中的这些对象不一定是实际的常量,而是按它们的目的使用(并且可以被认为)。
最佳答案
将其设置为 attribute on the function :
def foo(bar):
return foo.my_map.get(bar, defaultType)()
foo.my_map = {"rab": barType, "oof": fooType}
在我看来,可调用类或闭包不够简单。
关于python - 在python中,如何只为函数存储一次 'constants'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15495376/