什么是这个C/C++代码的惯用Python等价物?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
Run Code Online (Sandbox Code Playgroud)
具体来说,如何在功能级别实现静态成员,而不是类级别?将函数放入类中会改变什么吗?
没有多少人知道这个功能,但Python的功能(和方法)可以有属性.看吧:
>>> def foo(x):
... pass
...
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score']
>>> foo.score
10
>>> foo.score += 1
>>> foo.score
11
Run Code Online (Sandbox Code Playgroud)
Python中此功能的可能用途和滥用情况是什么?我知道的一个好用途是PLY使用docstring将语法规则与方法相关联.但是自定义属性呢?有充分的理由使用它们吗?
请考虑以下代码:
def CalcSomething(a):
if CalcSomething._cache.has_key(a):
return CalcSomething._cache[a]
CalcSomething._cache[a] = ReallyCalc(a)
return CalcSomething._cache[a]
CalcSomething._cache = { }
Run Code Online (Sandbox Code Playgroud)
这是我在python中模拟"局部静态"变量时最容易想到的方法.
让我困扰的是,CalcSomething._cache是函数的定义之外被提及,但另一种方法是类似的东西:
if not hasattr(CalcSomething, "_cache"):
setattr(CalcSomething, "_cache", { } )
Run Code Online (Sandbox Code Playgroud)
在函数的定义中,这真的很麻烦.
有更优雅的方式吗?
[编辑]
只是为了澄清,这个问题不是关于本地函数缓存,正如上面的例子所暗示的那样.这是另一个简短的例子,其中'静态本地'可能很方便:
def ParseString(s):
return ParseString._parser.parse(s)
# Create a Parser object once, which will be used for all parsings.
# Assuming a Parser object is heave on resources, for the sake of this example.
ParseString._parser = Parser()
Run Code Online (Sandbox Code Playgroud) 在C++中我们有静态关键字,在循环中是这样的:
for(int x=0; x<10; x++)
{
for(int y=0; y<10; y++)
{
static int number_of_times = 0;
number_of_times++;
}
}
Run Code Online (Sandbox Code Playgroud)
这里静态number_of_times
初始化一次.我怎么能在python 3.x中做同样的事情?
编辑:由于大多数人感到困惑,我想指出我给出的代码只是C++静态用法的一个例子.我真正的问题是我想在函数中只初始化一个时间变量,因为我不希望它是全局的(等等!)或默认参数..
我学会了实现二叉搜索树的中序遍历:
def inorder(root): # root has val, left and right fields
if root==None:
return
inorder(root.left)
print(root.val)
inorder(root.right)
Run Code Online (Sandbox Code Playgroud)
现在,问题是我不想要控制台输出。我想获取列表中的值。我找不到让函数返回列表的方法。
我试过了,s = [inorder(root)]
但没有用。
所以,我的问题是:
任何方式都可以在 inorder 函数内完成,即它应该返回一个列表而不仅仅是打印值。
是否有一些通用方法可以使递归函数返回数据结构,而不仅仅是将打印输出到控制台?
python algorithm recursion binary-search-tree data-structures