如何在Python中的函数调用之间维护列表和字典?

发布于 2024-07-11 12:38:24 字数 393 浏览 9 评论 0原文

我有一个功能。 在里面我维护着一个值字典。 我希望在不同的函数调用之间维护该字典

假设 dic 是:

a = {'a': 1, 'b': 2, 'c': 3}

在第一次调用时,我将 a['a'] 更改为 100。Dict

变为 a = {'a ':100,'b':2,'c':3}

在另一次通话中,我将 a['b'] 更改为 200。

我希望该 dic 为 a = {'a': 100, 'b': 200, 'c': 3}

但在我的代码中 a['a'] 不再保持 100。它更改为初始值 1。

I have a function. Inside that I'm maintainfing a dictionary of values.
I want that dictionary to be maintained between different function calls

Suppose the dic is:

a = {'a': 1, 'b': 2, 'c': 3}

At first call, say, I changed a['a'] to 100.

Dict becomes a = {'a': 100, 'b': 2, 'c': 3}.

At another call, I changed a['b'] to 200.

I want that dic to be a = {'a': 100, 'b': 200, 'c': 3}

But in my code a['a'] doesn't remain 100. It changes to initial value 1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

滥情哥ㄟ 2024-07-18 12:38:24

您可能正在谈论可调用对象。

class MyFunction( object ):
    def __init__( self ):
        self.rememberThis= dict()
    def __call__( self, arg1, arg2 ):
        # do something
        rememberThis['a'] = arg1
        return someValue

myFunction= MyFunction()

从那时起,将 myFunction 作为简单函数使用。 您可以使用 myFunction.rememberThis 访问 rememberThis 字典。

You might be talking about a callable object.

class MyFunction( object ):
    def __init__( self ):
        self.rememberThis= dict()
    def __call__( self, arg1, arg2 ):
        # do something
        rememberThis['a'] = arg1
        return someValue

myFunction= MyFunction()

From then on, use myFunction as a simple function. You can access the rememberThis dictionary using myFunction.rememberThis.

北斗星光 2024-07-18 12:38:24

您可以使用 静态变量

def foo(k, v):
  foo.a[k] = v
foo.a = {'a': 1, 'b': 2, 'c': 3}

foo('a', 100)
foo('b', 200)

print foo.a

You could use a static variable:

def foo(k, v):
  foo.a[k] = v
foo.a = {'a': 1, 'b': 2, 'c': 3}

foo('a', 100)
foo('b', 200)

print foo.a
万劫不复 2024-07-18 12:38:24

与在代码库上强制使用全局变量(这可能是调用者的决定)相比,我更喜欢保持与函数实例相关的状态的想法。 类对此很有用,但不能很好地传达您想要完成的任务,并且可能有点冗长。 在我看来,利用闭包要干净得多。

def function_the_world_sees():
    a = {'a':1,'b':2,'c':3}

    def actual_function(arg0, arg1):
        a[arg0] = arg1
        return a

    return actual_function
stateful_function = function_the_world_sees()

stateful_function("b", 100)    
stateful_function("b", 200)

要记住的主要注意事项是,当您在“actual_function”中进行分配时,它们会发生在“actual_function”中。 这意味着您不能将 a 重新分配给不同的变量。 我使用的解决方法是将我计划重新分配的所有变量放入每个变量的单个元素列表或字典中。

Rather than forcing globals on the code base (that can be the decision of the caller) I prefer the idea of keeping the state related to an instance of the function. A class is good for this but doesn't communicate well what you are trying to accomplish and can be a bit verbose. Taking advantage of closures is, in my opinion, a lot cleaner.

def function_the_world_sees():
    a = {'a':1,'b':2,'c':3}

    def actual_function(arg0, arg1):
        a[arg0] = arg1
        return a

    return actual_function
stateful_function = function_the_world_sees()

stateful_function("b", 100)    
stateful_function("b", 200)

The main caution to keep in mind is that when you make assignments in "actual_function", they occur within "actual_function". This means you can't reassign a to a different variable. The work arounds I use are to put all of my variables I plan to reassign into either into a single element list per variable or a dictionary.

塔塔猫 2024-07-18 12:38:24

如果在函数内部创建“a”。 它超出了范围。 只需在函数外部(并且在调用函数之前)创建它即可。 通过这样做,在程序离开该函数后,列表/哈希将不会被删除。

a = {'a':1,'b':2,'c':3}

# call you funciton here

If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function.

a = {'a':1,'b':2,'c':3}

# call you funciton here
温柔戏命师 2024-07-18 12:38:24

在我看来,这个问题没有一个优雅的答案。 这些选项是可调用对象、默认值和属性 hack。 可调用对象是正确的答案,但它们为另一种语言中的单个“静态”声明带来了很多结构。 默认值是对代码的一个小改动,但它很混乱,并且可能会让新的 Python 程序员在查看代码时感到困惑。 我不喜欢它们,因为它们的存在不会对任何可能查看您的 API 的人隐藏。

我通常会选择属性 hack。 我的首选方法是:

def myfunct():
    if not hasattr(myfunct, 'state'): myfunct.state = list()
    # access myfunct.state in the body however you want

这将状态声明保留在其所属函数的第一行,并将 myfunct 保留为函数。 缺点是每次调用该函数时都要进行属性检查。 这几乎肯定不会成为大多数代码中的瓶颈。

This question doesn't have an elegant answer, in my opinion. The options are callable objects, default values, and attribute hacks. Callable objects are the right answer, but they bring in a lot of structure for what would be a single "static" declaration in another language. Default values are a minor change to the code, but it's kludgy and can be confusing to a new python programmer looking at your code. I don't like them because their existence isn't hidden from anyone who might be looking at your API.

I generally go with an attribute hack. My preferred method is:

def myfunct():
    if not hasattr(myfunct, 'state'): myfunct.state = list()
    # access myfunct.state in the body however you want

This keeps the declaration of the state in the first line of the function where it belongs, as well as keeping myfunct as a function. The downside is you do the attribute check every time you call the function. This is almost certainly not going to be a bottleneck in most code.

空城仅有旧梦在 2024-07-18 12:38:24

您可以使用 Python 的默认参数行为进行“欺骗”。 默认参数仅计算一次; 它们会在函数的每次调用中被重用。

>>> def testFunction(persistent_dict={'a': 0}):
...     persistent_dict['a'] += 1
...     print persistent_dict['a']
...
>>> testFunction()
1
>>> testFunction()
2

这不是最优雅的解决方案; 如果有人调用该函数并传入参数,它将覆盖默认值,这可能不是您想要的。

如果您只是想要一种快速而肮脏的方法来获得结果,那么这是可行的。 如果你正在做一些更复杂的事情,最好将其分解到 S. Lott 提到的类中。

编辑:重命名了字典,这样它就不会按照下面的评论隐藏内置的 dict

You can 'cheat' using Python's behavior for default arguments. Default arguments are only evaluated once; they get reused for every call of the function.

>>> def testFunction(persistent_dict={'a': 0}):
...     persistent_dict['a'] += 1
...     print persistent_dict['a']
...
>>> testFunction()
1
>>> testFunction()
2

This isn't the most elegant solution; if someone calls the function and passes in a parameter it will override the default, which probably isn't what you want.

If you just want a quick and dirty way to get the results, that will work. If you're doing something more complicated it might be better to factor it out into a class like S. Lott mentioned.

EDIT: Renamed the dictionary so it wouldn't hide the builtin dict as per the comment below.

踏月而来 2024-07-18 12:38:24

就我个人而言,我喜欢全球声明的想法。 它没有引入全局变量,但声明本地标识符实际上引用全局命名空间中的标识符。

d = dict()
l = list()
def foo(bar, baz):
    global d
    global l
    l.append(bar, baz)
    d[bar] = baz

在python 3.0中还有一个“nonlocal”的说法。

Personally, I like the idea of the global statement. It doesn't introduce a global variable but states that a local identifier actually refers to one in the global namespace.

d = dict()
l = list()
def foo(bar, baz):
    global d
    global l
    l.append(bar, baz)
    d[bar] = baz

In python 3.0 there is also a "nonlocal" statement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文