Python中的静态变量? [英] static variables in Python?

查看:107
本文介绍了Python中的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




又一个菜鸟问题...


有没有办法在Python中模仿C'的静态变量?或者是什么

喜欢它?我们的想法是为一个给定的函数配备一组仅属于它的

常量,以免混淆全局

名称空间中包含其他地方不需要的变量。 。


例如,在Perl中可以定义一个像这样的函数foo


* foo = do {

我的$ x = expensive_call();

sub {

返回do_stuff_with($ x,@_);

}

};


在这种情况下,foo是通过为其分配一个闭包来定义的,该闭包具有关联变量$ x,其中包含$ x范围。


Python中是否有等价物?


谢谢!


kynn

-

注意:在我的地址中,第一个时期之前的所有内容都是向后的;

和最后一个时期以及之后的所有内容都应该被丢弃。

解决方案

x = expensive_call();

sub {

返回do_stuff_with(

X, @_);

}

};


在这种情况下,foo是通过为其分配一个闭包来定义的

一个关联的变量,


x,在它的范围内。


Python中是否有等价的?


谢谢!


kynn

-

注意:在我的地址中所有内容之前第一个时期是倒退;

和最后一个时期以及之后的所有时期都应该被丢弃。




Yet another noob question...

Is there a way to mimic C''s static variables in Python? Or something
like it? The idea is to equip a given function with a set of
constants that belong only to it, so as not to clutter the global
namespace with variables that are not needed elsewhere.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call();
sub {
return do_stuff_with( $x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.

解决方案

x = expensive_call();
sub {
return do_stuff_with(


x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable,


x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.


这篇关于Python中的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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