Python中的静态变量? [英] Static variable in Python?

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

问题描述

在 C++ 中,我们有 static 关键字,它在循环中是这样的:

In C++ we have static keyword which in loops is something like this:

for(int x=0; x<10; x++)
    {
      for(int y=0; y<10; y++)
      {
        static int number_of_times = 0;
        number_of_times++;
      }
    }

static 这里使 number_of_times 初始化一次.我如何在 python 3.x 中做同样的事情?

static here makes number_of_times initialized once. How can I do same thing in python 3.x?

由于大多数人感到困惑,我想指出我提供的代码只是 C++ 中静态用法的示例.我真正的问题是我只想在函数中初始化一个时间变量,因为我不希望它是全局变量(等等!)或默认参数..

Since most of the people got confused I would like to point out that the code I gave is just example of static usage in C++. My real problem is that I want to initialize only ONE time variable in function since I dont want it to be global(blah!) or default parameter..

推荐答案

假设您想要的是在第一次函数调用时仅初始化一次的变量",Python 语法中没有这样的东西.但是有一些方法可以获得类似的结果:

Assuming what you want is "a variable that is initialised only once on first function call", there's no such thing in Python syntax. But there are ways to get a similar result:

1 - 使用全局.请注意,在 Python 中,全局"实际上意味着模块全局",而不是进程全局":

1 - Use a global. Note that in Python, 'global' really means 'global to the module', not 'global to the process':

_number_of_times = 0

def yourfunc(x, y):
    global _number_of_times
    for i in range(x):
        for j in range(y):
            _number_of_times += 1

2 - 将您的代码包装在一个类中并使用一个类属性(即:所有实例共享的属性).:

2 - Wrap you code in a class and use a class attribute (ie: an attribute that is shared by all instances). :

class Foo(object):
    _number_of_times = 0

    @classmethod
    def yourfunc(cls, x, y):
        for i in range(x):
            for j in range(y):
                cls._number_of_times += 1

请注意,我使用了 classmethod,因为此代码片段不需要来自实例的任何内容

Note that I used a classmethod since this code snippet doesn't need anything from an instance

3 - 将您的代码包装在一个类中,使用实例属性并为该方法提供快捷方式:

3 - Wrap you code in a class, use an instance attribute and provide a shortcut for the method:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def yourfunc(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1

yourfunc = Foo().yourfunc

4 - 编写一个可调用的类并提供一个快捷方式:

4 - Write a callable class and provide a shortcut:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def __call__(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1


yourfunc = Foo()

4 之二 - 使用类属性和元类

4 bis - use a class attribute and a metaclass

class Callable(type):
    def __call__(self, *args, **kw):
        return self._call(*args, **kw)

class yourfunc(object):
    __metaclass__ = Callable

    _numer_of_times = 0

    @classmethod
    def _call(cls, x, y):
        for i in range(x):
            for j in range(y):                 
                cls._number_of_time += 1

5 - 创造性地"使用在模块导入时仅实例化一次的函数默认参数:

5 - Make a "creative" use of function's default arguments being instantiated only once on module import:

def yourfunc(x, y, _hack=[0]):
    for i in range(x):
        for j in range(y):
            _hack[0] += 1

还有一些其他可能的解决方案/技巧,但我认为您现在已经了解了全局.

There are still some other possible solutions / hacks, but I think you get the big picture now.

鉴于操作的澄清,即假设您有一个带有默认参数的递归函数,但如果有人实际上试图为您的函数提供更多参数,这可能是灾难性的",看起来 OP 真正想要的是类似:

given the op's clarifications, ie "Lets say you have a recursive function with default parameter but if someone actually tries to give one more argument to your function it could be catastrophic", it looks like what the OP really wants is something like:

# private recursive function using a default param the caller shouldn't set
def _walk(tree, callback, level=0):
    callback(tree, level)
    for child in tree.children:
        _walk(child, callback, level+1):

# public wrapper without the default param
def walk(tree, callback):
    _walk(tree, callback)

顺便说一句,这证明我们确实遇到了另一个 XY 问题......

Which, BTW, prove we really had Yet Another XY Problem...

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

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