[英]Python -local variable '' referenced before assignment
I'm trying to figure out some problem I have. 我正在尝试找出我遇到的一些问题。 I have written small program just for the example here (which i'll implement the solution in the real one :) ) 我已经为此处的示例编写了小程序(我将在实际示例中实现该解决方案:))
So, I have 3 files One -Which is the main Test -Which is the test I run CounterTest -Which has class with def inside 因此,我有3个文件一个-哪个是主测试-哪个是我运行的测试CounterTest-哪个具有带有def的类
One: 一:
def main():
CounterTest=1
execfile("c:\\111\\Test.py")
if __name__ == '__main__':
main()
Test: 测试:
from CounterTest import *
print "THIS IS THE TEST"
CallClass=CounterTest1()
CallClass.CounterPlus()
CounterTest: 反测试:
class CounterTest1():
def CounterPlus(self):
CounterTest +=1
print CounterTest
Scenario: I run "one" which execute file Test (All this happen in main def) In "Test" I'm calling class and def -in def we counter +1 , that was defined in "one" file. 场景:我运行执行文件Test的“一个”(所有这些都发生在main def中)在“ Test”中,我调用class和def -in def我们对+1进行了定义,这是在“一个”文件中定义的。
I'm getting "local variable 'CounterTest' referenced before assignment" 我收到“分配前已引用本地变量'CounterTest'”
I have tried everything but nothing worked 我已经尝试了一切,但无济于事
Appriciated , 申请,
Thanks 谢谢
The long and short of it is that you can't. 它的长短是你不能。 If I'm understanding your process correctly you are: 如果我正确了解您的流程,则您是:
1. Running main.py
. 1.运行main.py
2. Defining the variable INSIDE a function so it's non-global 2.在函数中定义变量,使其不全局
def main():
CounterTest = 1 # <-- right here
3. Executing code from a different file 3.从其他文件执行代码
execfile("...")
4. Which imports a THIRD file 4.导入第三文件
from CounterTest import *
5. That attempts to modify a global in the first file 5.尝试在第一个文件中修改全局
...
CounterTest += 1
You can't do that. 你不能那样做。 You're three levels of "nope" away from that. 距离这三个级别的“不”。
main.py
's CounterTest
isn't a global, so it's only available inside def main
's scope. main.py
的CounterTest
不是全局的,因此仅在def main
的作用域内可用。 test.py
doesn't have access to main.py
's globals without passing them explicitly. 即使它是全局的, test.py
也不能在未显式传递它们的情况下访问main.py
的全局变量。 execfile(path, globals_dict, locals_dict)
), and they became globals inside test.py
, CounterTest.py
isn't allowed to see test.py
's globals. 即使您显式传递了它们(使用execfile(path, globals_dict, locals_dict)
),并且它们成为test.py
内部的全局变量, CounterTest.py
也不允许查看test.py
的全局变量。 You can't even monkey around with things to make that okay. 您甚至无法四处寻找使之正常的事情。 You need to paramaterize values and you need to stop using globals. 您需要对值进行参数化,并且需要停止使用全局变量。 This whole thing SHOULD be: 这整个事情应该是:
# counter.py
class Counter(object):
"""Counter is knows how to add to itself"""
def __init__(self, value=1):
self.__value = value
def increment(self):
self.__value += 1
@property
def value(self):
return self.__value
# main.py
import counter
c = counter.Counter() # initializes at 1
print(c.value) # 1
c.increment()
print(c.value) # 2
# now SHARE that instance of c!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.