什么是在函数调用之间保存数据的pythonic方法?

时间:2017-02-03 07:39:20

标签: python variables state

对我而言,上下文是我需要在调用该值的函数之间保留的单个int值的信息。我可以使用全球,但我知道这是沮丧的。现在我已经使用了包含int的列表形式的默认参数,并利用了可变性,以便在调用之间保留对值的更改,如下所示 -

 def increment(val, saved=[0]):
    saved[0] += val
    # do stuff

此功能通过tkinter附加到按钮,就像这样〜

button0 = Button(root, text="demo", command=lambda: increment(val))

这意味着我没有返回值可以分配给函数外部的局部变量。

人们通常如何处理这个问题?我的意思是,当然,可变性技巧可以工作,但是如果我需要从多个函数中访问和修改该值,该怎么办?

如果没有使用静态方法和内部属性等设置类,是否可以这样做?

4 个答案:

答案 0 :(得分:5)

使用课程。使用实例成员来保持状态。

class Incrementable:
    def __init__(self, initial_value = 0):
        self.x = initial_value
    def increment(self, val):
        self.x += val
        # do stuff

您可以添加__call__方法来模拟函数调用(例如,如果您需要向后兼容)。这是否是一个好主意实际上取决于具体情况和具体用例。

  

如果没有使用静态方法和内部属性等设置类,是否可以这样做?

可以,但不涉及具有属性的类/对象的解决方案不是“pythonic”。在python中定义类很容易(上面的例子只有5条简单的行),它给你最大的控制和灵活性。

使用python的mutable-default-args "weirdness"(我不会称之为“功能”)应被视为 a hack

答案 1 :(得分:1)

你不是在混淆模特和观点吗?

UI元素(如按钮)应该只委托给您的数据模型。因此,如果你有一个具有持久状态的模型(即带有属性的类),你可以在那里实现一个类方法,如果单击一个按钮就可以处理所需的东西。

如果您尝试将有状态事物绑定到演示文稿(UI),您将因此失去所述演示文稿与数据模型之间的理想分离。

如果您希望简化数据模型访问,可以考虑singleton实例,这样您就不需要将对该模型的引用作为所有UI元素的参数(加上你不需要一个全局实例,即使这个singleton拥有某种全局可用的实例):

def singleton(cls):
    instance = cls()
    instance.__call__ = lambda: instance
    return instance

@singleton
class TheDataModel(object):
    def __init__(self):
        self.x = 0

    def on_button_demo(self):
        self.x += 1

if __name__ == '__main__':
    # If an element needs a reference to the model, just get
    # the current instance from the decorated singleton:
    model = TheDataModel
    print('model', model.x)
    model.on_button_demo()
    print('model', model.x)

    # In fact, it is a global instance that is available via
    # the class name; even across imports in the same session
    other = TheDataModel
    print('other', other.x)

    # Consequently, you can easily bind the model's methods
    # to the action of any UI element
    button0 = Button(root, text="demo", command=TheDataModel.on_button_demo)

但是,我必须指出这一点,在使用singleton实例时要小心,因为它们很容易导致设计错误。设置一个合适的模型,只需访问主要模型化合物singleton即可。这种统一访问通常称为 context

答案 2 :(得分:1)

如果您不想设置类,那么您唯一的 1 其他选项是全局变量。您无法将其保存到本地变量,因为该命令在mainloop内运行,而不是在创建它的本地范围内运行。

例如:

button0 = Button(root, text="demo", command=lambda: increment_and_save(val))

def increment_and_save(val):
    global saved
    saved = increment(val)

1 不是字面意义,因为您可以使用各种其他方式来保存数据,例如数据库或文件,但我认为您需要内存解决方案。

答案 3 :(得分:0)

我们可以使用context managers使其面向上下文。示例并非特定于UI元素,但是表示一般情况。

class MyContext(object):
    # This is my container 
    # have whatever state to it
    # support different operations

    def __init__(self):
        self.val = 0

    def increament(self, val):
        self.val += val

    def get(self):
        return self.val

    def __enter__(self):
        # do on creation
        return self


    def __exit__(self, type, value, traceback):
        # do on exit
        self.val = 0

def some_func(val, context=None):
    if context:
        context.increament(val)

def some_more(val, context=None):
    if context:
        context.increament(val)

def some_getter(context=None):
    if context:
        print context.get()

with MyContext() as context:
    some_func(5, context=context)
    some_more(10, context=context)
    some_getter(context=context)
相关问题