python中的全球变量

ran*_*afk 0 python global

我目前有一些类foo(),其中包含一些变量,这些变量不仅在foo类的所有实例之间共享,而且还由其他类bar共享.

class foo():
    __init__(self, a, b):
        self.a = a
        self.b = b

class bar():
    __init__(self, a, b):
        self.a = a
        self.b = b
Run Code Online (Sandbox Code Playgroud)

一种解决方案是制作a和b类变量,但如何在构造期间干净利落地做到这一点?我可以将两个类放在同一个文件中并让它们引用一些全局变量a和b吗?这是不好的做法吗?

Ela*_*zar 6

由于您没有提供您的意图或现实情况,我将提供一些共享变量访问的方法.

第一种选择:全球.

a=b=None

class foo():
    def __init__(self, _a, _b):
        global a, b
        a, b = _a, _b

class bar():
    def __init__(self, _a, _b):
        global a, b
        a, b = _a, _b
Run Code Online (Sandbox Code Playgroud)

第二个选项:foo的班级变量

class foo():
    a = b = None
    def __init__(self, a, b):
        foo.a, foo.b = a, b

class bar():
    def __init__(self, a, b):
        foo.a, foo.b = a, b
Run Code Online (Sandbox Code Playgroud)

第三种选择:继承

class foo():
    def __init__(self, a, b):
        self.a, self.b = a, b

class bar(foo):
    pass
Run Code Online (Sandbox Code Playgroud)

第四种选择:外类

class outer():
    a = b = None
    class foo():
        def __init__(self, a, b):
            outer.a, outer.b = a, b

    class bar():
        def __init__(self, a, b):
            outer.a, outer.b = a, b
Run Code Online (Sandbox Code Playgroud)

第五种选择:compsition

class foo():
    def __init__(self, a, b):
        self.a, self.b = a, b

class bar():
    def __init__(self, a, b):
        self.foo = foo(a,b)
Run Code Online (Sandbox Code Playgroud)

第6个选项:关闭外部函数局部变量

def outer():
    a = b = None
    class foo():
        def __init__(self, _a, _b):
            nonlocal a, b
            a, b = _a, _b

    class bar():
        def __init__(self, _a, _b):
            nonlocal a, b
            a, b = _a, _b

    ... #things with foo and bar
Run Code Online (Sandbox Code Playgroud)

第7个选项:关闭foo的__init__局部变量.

class foo():
    def __init__(self, a, b):
        self.a, self.b = a, b
        class bar():
            nonlocal a, b
            #do things with a and b directly

        self.bar = bar()
Run Code Online (Sandbox Code Playgroud)

  • 你错过了很多`def`s.另外,你的第五个选择是错误的; 你想要像'self.foo = foo(a,b)`这样的东西.而你的第6个也是.我不确定你在那里尝试了什么,但是该代码只是将`a`和`b`重新绑定到传递给任一类的每个初始化的实际参数.此外,第7个就像第6个功能本地一样; 只是你正在使用隐式`nonlocal`(或者,如果你分配给`a`或`b`,而不是......),并且捕获闭包可能会在以后使用. (2认同)