Daniel이 말한 것처럼 전역 변수를 사용하는 것은 나쁘지 않습니다. 그러나 문제를 해결했기 때문에이를 사용한다고해서 전역 변수를 제대로 사용할 수는 없습니다.
위의 예에서는 다음과 같은 세 가지 조건이 있음을 알았습니다. 1) 항목 목록을 생성하는 함수가 필요합니다. 2) 두 번째 함수가 있습니다. 첫 번째 기능) 3) 해당 항목을 확인할 수 있기를 원합니다.
그 중 어느 것도 글로벌 필요성을 나타내지 않지만 클래스가 문제를 해결할 수 있습니다.나는 비슷한 클래스를 사용하는 것이 좋습니다 것 I는 다음과 같습니다
from threading import Thread # To thread the build logic
import random # For random numbers to increase entrophy
import time
class builder(object):
def __init__(self, numObjs):
self.myList = []
self.numObjs = int(numObjs)
self.inProcess = False
# Build a list of objects
def build(self):
if self.currStatus(False) and self.inProcess == False:
self.inProcess = True
self.currGenThread = Thread(target=self.generate)
self.currGenThread.start()
else:
print "Failed to start new thread -- current thread in process!"
# Generates the objects for the list
def generate(self):
import random, time # Note: Solves thread "not defined" issues
self.myList = []
for currObj in range(self.numObjs):
self.myList.append(currObj)
time.sleep(random.randint(0,1)) # Sleep randomly
# Prints the current status
# Return False indicates completion
def currStatus(self, alsoPrint=True):
retVal = True
if len(self.myList) >= self.numObjs:
if self.currGenThread:
self.currGenThread.join()
self.inProcess = False
retVal = False
# Print status if called for
if alsoPrint:
print "Progress %d -- %s" % (len(self.myList)/self.numObjs,
str(self.myList))
return retVal
obj = builder(10)
obj.build()
while obj.currStatus():
time.sleep(1)
그것은 완벽한 예 아니지만, 당신이 그 코드를 실행하면이 같은 얻을 :
$python test.py
Progress 0 -- []
Progress 0 -- [0, 1, 2, 3]
Progress 0 -- [0, 1, 2, 3, 4]
Progress 0 -- [0, 1, 2, 3, 4, 5]
Progress 0 -- [0, 1, 2, 3, 4, 5, 6]
Progress 0 -- [0, 1, 2, 3, 4, 5, 6, 7, 8]
Progress 1 -- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
python test.py
Progress 0 -- []
Progress 0 -- [0, 1]
Progress 0 -- [0, 1, 2, 3, 4, 5, 6, 7]
Progress 1 -- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
당신은 할 수 있습니다 지구 적으로나 다른 여러면에서 똑같은 것. 잘하면이 도움이됩니다.
"빌드"와 항목 목록 생성의 차이점을 이해하지 못합니다. – deets
당신은 클래스 인스턴스를 설명하는 것처럼 들리지만, afterall은 사전으로 구현됩니다. –
generate를 사용하면 목록을 계산하지만 메모리에 보관하면된다는 의미입니다. 그런 다음 목록을 사용하여 무언가를 할 수 있습니다. 그리고 클래스 인스턴스는 모든 것과 분리되어 있습니다.하지만 원하는 변수 이름을 지정하면 리턴됩니다. – Peter