使用Class:Python创建类

时间:2014-12-29 02:14:58

标签: python multithreading class

我正在尝试实现消费者 - python中的生产者问题...我遇到的一个问题是我是否可以在类中创建一个类并在外部作用域中创建它的对象,如下面的代码中所示...

class Main(threading.Thread):
    def __init__(self):
        processNumber = 0
        queue_size=5
        self.mutexProducer=thread.allocate_lock()#mutex variablaes
        self.mutexConsumer=thread.allocate_lock()
        self.mutexTeller=thread.allocate_lock()
        self.queue=Queue.Queue(maxsize=queue_size)
        self.producer=Producer(processNumber,random.random())

class Producer(threading.Thread):
    def __int__(self,ProducerID,serviceTime):
        self.id=ProcucerID
        self.serviceTime=serviceTime
    def run(self):
            #mutexProducer.acquire()
            #Entering Critical section
        print queue.qsize()
        if queue.full():
            sleep(random.random())
        else:
            print "Customer %d Enters the Queue" %(self.id)



app=Main()

我收到以下错误

  
    

回溯(最近一次呼叫最后):文件" /Users/sohil/Desktop/sync.py",第55行,在         app = Main()文件" /Users/sohil/Desktop/sync.py",第36行, init         self.producer = Producer(processNumber,random.random())NameError:全局名称'制作人'未定义

  

1 个答案:

答案 0 :(得分:0)

更改订单。

class Producer(threading.Thread):
    def __int__(self,ProducerID,serviceTime):
        self.id=ProcucerID
        self.serviceTime=serviceTime
    def run(self):
            #mutexProducer.acquire()
            #Entering Critical section
        print queue.qsize()
        if queue.full():
            sleep(random.random())
        else:
            print "Customer %d Enters the Queue" %(self.id)

class Main(threading.Thread):
    def __init__(self):
        processNumber = 0
        queue_size=5
        self.mutexProducer=thread.allocate_lock()#mutex variablaes
        self.mutexConsumer=thread.allocate_lock()
        self.mutexTeller=thread.allocate_lock()
        self.queue=Queue.Queue(maxsize=queue_size)
        self.producer=Producer(processNumber,random.random())

Python是一种解释性语言,从上到下执行,因此必须在顶部声明任何依赖项。