Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的状态变量:何时选择类、非局部变量或函数属性_Python_Class_Python Nonlocal_Function Attributes - Fatal编程技术网

Python中的状态变量:何时选择类、非局部变量或函数属性

Python中的状态变量:何时选择类、非局部变量或函数属性,python,class,python-nonlocal,function-attributes,Python,Class,Python Nonlocal,Function Attributes,有(至少)三种不同的方法来跟踪python中函数的状态信息(显然,示例中没有任何有意义的方法来使用状态信息): 面向对象类: class foo: def __init__(self, start): self.state = start # whatever needs to be done with the state information 非局部变量(Python 3): 或功能属性: def foo(start): def bar(bar.st

有(至少)三种不同的方法来跟踪python中函数的状态信息(显然,示例中没有任何有意义的方法来使用状态信息):

面向对象类:

class foo:
    def __init__(self, start):
        self.state = start
    # whatever needs to be done with the state information
非局部变量(Python 3):

或功能属性:

def foo(start):
    def bar(bar.state):
        # whatever needs to be done with the state information
    bar.state = start
    return bar
我理解每种方法是如何工作的,但我无法解释的是,为什么(除了熟悉程度)你会选择一种方法而不是另一种。继Python的Zen之后,类似乎是最优雅的技术,因为它不再需要嵌套函数定义。然而,与此同时,类可能会引入比需要更多的复杂性


在权衡在程序中使用哪种方法时应该考虑什么?

我总是选择一个类,因为它的使用方式,而不是它的实现方式。当我实例化一个类时,我希望该实例可以保留一些状态信息。这就是类实例所做的。当我调用一个函数时,我通常希望无论何时使用相同的参数调用它,它都会返回相同的结果,因此如果它保持状态,这将是意外的,并可能导致我(调用方)的代码中出现错误,尽管如果有很好的文档记录,即使这种行为也不是完全错误的。问题可能过于广泛,但作为一般规则,在担心其他两个类之前,您应该有一个坚实、具体的理由不使用该类。(而且函数属性几乎是您正在使用的任何实现的意外事件,而不是有意使用的东西。)顺便说一句,不要担心“类可能会引入比需要更多的复杂性”。大多数复杂性来自我的经验中缺乏清晰性。请记住,每次调用
foo
时,您的函数
bar
都会重新定义。同意类是最清晰的。我发现
非本地
很难推理。此外,函数属性的使用看起来像穷人的类。更好地使用函数属性的是文档:
def foo(start):
    def bar(bar.state):
        # whatever needs to be done with the state information
    bar.state = start
    return bar