python 定义常量函数_在python中,如何只为函数存储“常量”?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值