在python中,如何只为函数存储“常量”? [英] In python, how to store 'constants' for functions only once?

查看:408
本文介绍了在python中,如何只为函数存储“常量”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些函数需要常量值(即未设计为稍后重新定义),这些值不会被参数化。虽然默认参数仅存储 每个函数,有些只是作为参数放在一个非常有意义的位置(也就是签名)。对于(一个不是很有用的)例子:

pre $ def foo(bar):
my_map = {rab: barType,oof:fooType}
return my_map.get(bar,defaultType)()



<浪费了CPU时间和RAM空间来为每次调用重新定义这样一个常量。其他一些方法是将这些常量存储为模块级全局变量,或者将该函数设置为可调用的类,但是可能有其他方法,也许是?

在做时模块级别的全局方式,我用我的(意思是一个)常量变量加上_来表示为了任何人的兴趣,它在那里 not 。尽管如此,我还是觉得模块名称空间稍微有些被污染了,而不是说使用 a> 不如全局一样:

  _my_map = {rab:barType,oof:fooType} 
def foo(bar):
return _my_map.get(bar,defaultType)()

或者将其转换为类的方式。我让 __调用__ classmethod ,以避免创建实例:

  class foo:
my_map = {rab:barType,oof:fooType}
@classmethod
def __call __(cls,bar):
return cls.my_map.get(bar,defaultType)()

这些解决方案pythonic够了吗?

还有其他方法可以做到这一点吗?



作为使用这种常量的练习,它甚至可以吗?

在我的例子中,这些对象不一定是实际的常量,而是根据它们的用途使用(并且可以被认为是)。

解决方案

将其设置为函数的属性:

  def foo(bar):
return foo.my_map.get(bar,defaultType)()
foo.my_map = {rab:barType,oof:fooType}

 



一个可调用的类或一个闭包并不简单IMO。


Some function need 'constant' values (ie. not designed to be redefined later) that are not to be parametrized. While default arguments are stored only once for each function, some are just not very meaningful to be put as parameters (ie. to be part of the signature). For (a not very useful) example:

def foo(bar):
    my_map = {"rab": barType, "oof": fooType}
    return my_map.get(bar,defaultType)()

It wasted CPU time and RAM space to re-define such a constant for each call. Some other ways are to store such constants as module level globals or make the function a callable class, but there may be other ways, maybe?

When doing the module level global way, I prefix my (meant as a) constant variable with a "_" to show that it is there not for anyone's interest. Still I feel the module namespace slightly "polluted", not to speak of the shame of using something as discouraged as globals at all:

_my_map = {"rab": barType, "oof": fooType}
def foo(bar):
    return _my_map.get(bar,defaultType)()

Or the transform it into a class way. I make the __call__ a classmethod, to avoid the need of creating instances:

class foo:
   my_map = {"rab": barType, "oof": fooType}
   @classmethod
   def __call__(cls,bar):
       return cls.my_map.get(bar,defaultType)()

Are these solutions pythonic enough?

Are there other ways to do this?

Is it even ok as a practice to use such 'constants'?

Note these objects in my examples are not necessarily actual constants, but used (and could be thought) as such by their purpose.

解决方案

Set it as an attribute on the function:

def foo(bar):
    return foo.my_map.get(bar, defaultType)()
foo.my_map = {"rab": barType, "oof": fooType}

 

A callable class or a closure is not simple enough IMO.

这篇关于在python中,如何只为函数存储“常量”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆