简体   繁体   English

更改不同文件中的全局变量

[英]change global variable in different files

I do not really understand how python handles global variables if the code is split into different files. 如果将代码拆分为不同的文件,我不太了解python如何处理全局变量。

Assuming I have 3 files: class1.py, class2.py, main.py 假设我有3个文件:class1.py,class2.py,main.py

In main.py I define a global variable 在main.py中,我定义了一个全局变量

from class1 import Class1
from class2 import Class2
global sys
sys = constructor()

This object contains information about the system which I simulate and is used and manipulated by the classes defined in class1.py and in class2.py. 该对象包含有关我所模拟的系统的信息,并且由class1.py和class2.py中定义的类使用和操纵该系统。

One could of course argue that this is bad style and one should avoid exploiting global variables like this, but this is not the point here. 当然可以说这是不好的风格,应该避免利用这样的全局变量,但这不是重点。

If now I use sys in either class, it is unknown. 如果现在我在任何一个类中都使用sys,则是未知的。 To use a global variable one could of course define them somewhere and then include this file. 要使用全局变量,当然可以在某处定义它们,然后包含此文件。 But then, the changes that are made by the classes would not effect each other, so I don't want to do this. 但是,这些类所做的更改不会互相影响,所以我不想这样做。

Another way would be to define a new Class SuperClass where sys is a member. 另一种方法是定义一个新的Class SuperClass,其中sys是成员。 If now Class1 and Class2 are inherited from SuperClass, I could probably do some stuff with the super keyword. 如果现在Class1和Class2是从SuperClass继承的,我可能可以用super关键字做一些事情。 I do not really want to do this... 我真的不想这么做...

Long story short... Is there a way to define an python object such, that it behaves similar to a C-style global variable? 长话短说...有没有办法定义一个python对象,使其行为类似于C样式的全局变量?

Maybe it helps if I give an example: 如果我举个例子,也许会有所帮助:

  • sys includes the system frequency sys包括系统频率
  • a function of Class1 changes the system frequency Class1的功能更改系统频率
  • a function of Class2 simulates stuff and uses the system frequency Class2的功能模拟东西并使用系统频率
  • based on this the system power is changed in sys 基于此,在sys中更改系统电源
  • a function of Class1 performs a task with updated system power Class1的功能以更新的系统功能执行任务

No, there's no way to have "C-style global variables", and that's by design. 不,没有办法拥有“ C样式的全局变量”,这是设计使然。 Explicitely pass your sys objects to Class1 and Class2 when instanciating them and you'll be done, with a clean, readable, testable, maintainable implementation: 实例化时,将sys对象显式传递给Class1和Class2,并且可以通过干净,可读,可测试,可维护的实现来完成:

# lib.py
class Class1(object):
    def __init__(self, sys, whatever):
        self.sys = sys
        # ...

class Class2(object):    
    def __init__(self, sys, whateverelse):
        self.sys = sys
        # ...


# main.py

from lib import Class1, Class2

def main():
    sys = constructor()
    c1 = Class1(sys, 42)
    c2 = Class(sys, "spam")

    # now you can work with c1 and c2

if __name__ == "__main__":
    main()

To answer your very first question: 要回答您的第一个问题:

I do not really understand how python handles global variables if the code is split into different files. 如果将代码拆分为不同的文件,我不太了解python如何处理全局变量。

Python's "globals" are module-level names. Python的“全局变量”是模块级别的名称。 At runtime, modules are objects (instances of the module type), and all names defined at the module's top level become attributes of the module instance - "defined" being either by assignment, by a def or class statement or by an import statement. 在运行时,模块是对象( module类型的实例),并且在模块顶层定义的所有名称均成为模块实例的属性-“定义”可以通过赋值,通过defclass语句或通过import语句来实现。

From within the module, top-level names are accessible by their unqualified names in all the module's code - you only need the global keyword if you want to rebind a top-level name from within a function. 从模块内部,顶级名称可以通过所有模块代码中的非限定名称进行访问-如果要从函数中重新绑定顶级名称,则仅需要global关键字。

From outside the module, you can access those names using the qualified path, ie if module1 defines name foo , you can access it from module2 by importing module1 (making module1 a top-level name in module2 ) and using the usual attribute resolution (dotted.name) syntax. 从模块外部,您可以使用限定路径访问这些名称,即,如果module1定义了名称foo ,则可以通过导入module1 (在module2中将module2 module1顶级名称)并使用通常的属性解析(点划线)从module2进行访问。 .name)语法。

You can also import foo directly using from module1 import foo , in which case a new name foo will be created in module2 and bound to module1.foo (more exactly: bound to the object which is at this point bound to module1.foo ). 您也可以使用from module1 import foo import foo直接from module1 import foo ,在这种情况下,将在module2创建一个新名称foo并绑定到module1.foo (更确切地说:绑定到此时绑定到module1.foo的对象)。 The point here is that you know have two distinct names in two distinct namespaces, so rebinding either will only affect the namespace in which it's rebound. 这里的要点是,您知道在两个不同的名称空间中有两个不同的名称,因此重新绑定其中任何一个只会影响其反弹的名称空间。

You certainly want to read Ned Batcheler's famous article on Python's names , it's usually a good starting point to understand all this. 您当然想阅读Ned Batcheler关于Python名称的著名文章 ,通常这是理解所有这些内容的一个很好的起点。

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

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