在我的例子中如何访问变量外部类?

dav*_*vid 1 python oop class python-2.7

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

    def house(self):
        d = self.a+self.b+self.c
        print d

module="hello"
p = testing(1, 2, 3)
p.house()
Run Code Online (Sandbox Code Playgroud)

如何module从我的testing班级中访问变量?我知道我可以通过执行以下操作将其作为参数添加到类构造函数中:

p=testing(1,2,3,module)
Run Code Online (Sandbox Code Playgroud)

但我不想这样做,除非我必须这样做.还有哪些方法可以moduletesting课堂内访问变量?

Pru*_*une 6

你只是引用它; 您无需任何特殊的全局权限即可访问它.这不是最好的方法,但由于您没有描述您的应用程序和模块化要求,我们现在可以做的就是解决您当前的问题.

顺便说一下,你的a,b,c引用是不正确的.见下文.

class testing():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.greeting = module

    def house(self):
        d = self.a + self.b + self.c
        print d
        print self.greeting

module="hello"
p = testing(1, 2, 3)
p.house()
Run Code Online (Sandbox Code Playgroud)

输出:

6
hello
Run Code Online (Sandbox Code Playgroud)