简体   繁体   English

为什么对象不需要全局关键字

[英]why is the global keyword not needed with an object

in this example i need to include the global keyword. 在此示例中,我需要包括global关键字。 I have read elsewhere on stack exchange that immutable objects need the global keyword. 我在堆栈交换的其他地方读过,不变的对象需要global关键字。

def foo(param):
    global message
    message += param

message = " hello "

foo("world")

print(message)

but in this example using lists which are mutable i also need the global keyword. 但在此示例中,使用可变的列表我需要global关键字。

def foo(param):
    global message
    message += [ param ]

message = [ "hello" ]

foo("world")

print(message)

but in this example I create a 'container' object which allows me to fore go the global keyword. 但是在此示例中,我创建了一个“容器”对象,该对象使我可以不使用global关键字。

class container:

    def __init__(self):
        self._message = ""

    def __str__(self):
        return self._message

    def add(self, param):
        self._message += param

def foo(param):
    message.add(param)

message = container()
message.add(" hello ")

foo("world")

print(message)

What are the rules for using the global keyword? 使用global关键字的规则是什么? This seems inconsistent 这似乎不一致

This frequently asked question has an answer in the official documentation: 这个常见问题在官方文档中有一个答案:

In Python, variables that are only referenced inside a function are implicitly global. 在Python中,仅在函数内部引用的变量是隐式全局的。 If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global. 如果在函数体内任何位置为变量分配了值,除非明确声明为全局变量,否则将假定该变量为局部变量。

Though a bit surprising at first, a moment's consideration explains this. 尽管起初有些令人惊讶,但片刻的考虑可以解释这一点。 On one hand, requiring global for assigned variables provides a bar against unintended side-effects. 一方面,要求全局分配变量可防止意外副作用。 On the other hand, if global was required for all global references, you'd be using global all the time. 另一方面,如果所有全局引用都需要全局,那么您将一直使用全局。 You'd have to declare as global every reference to a built-in function or to a component of an imported module. 您必须将对内置函数或导入模块的组件的每个引用声明为全局引用。 This clutter would defeat the usefulness of the global declaration for identifying side-effects. 这种混乱将破坏全球宣言对确定副作用的有用性。

See also the documentation on global for more details. 另请参阅有关global文档以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM