学习python中__name__方法使用

今天在自学生产者消费者模型时,发现了一个有趣的方法

if __name__ == "__main__":
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(10):
        c = Consumer()
        c.start()

于是就去确认了一下度娘,果然好多初学者都会问这个问题,思路解释如下:

1. 如果模块是被导入,__name__的值为模块名字
2. 如果模块是被直接执行,__name__的值为’__main__’

亦或有一些解释

1:__name__是一个变量。前后加了爽下划线是因为是因为这是系统定义的名字。普通变量不要使用此方式命名变量。
2:Python有很多模块,而这些模块是可以独立运行的!这点不像C++和C的头文件。
3:import的时候是要执行所import的模块的。
4:__name__就是标识模块的名字的一个系统变量。这里分两种情况:假如当前模块是主模块(也就是调用其他模块的模块),那么此模块名字就是__main__,通过if判断这样就可以执行“__mian__:”后面的主函数内容;假如此模块是被import的,则此模块名字为文件名字(不加后面的.py),通过if判断这样就会跳过“__mian__:”后面的内容。

通过上面方式,python就可以分清楚哪些是主函数,进入主函数执行;并且可以调用其他模块的各个函数等等。

上一段生产者消费者模型代码,来判断代码确认可以简化代码健壮性!

#encoding=utf-8
import threading
import time
condition = threading.Condition()
products = 0
class Producer(threading.Thread):
    '''生产者'''
    ix = [0]  # 生产者实例个数
    # 闭包,必须是数组,不能直接 ix = 0
    def __init__(self, ix=0):
        threading.Thread.__init__(self)
        self.ix[0] += 1
        self.setName('生产者' + str(self.ix[0]))
    def run(self):
        global condition, products
        while True:
            if condition.acquire():
                if products < 10:
                    products += 1;
                    print("{}:库存不足,我努力生产了1件产品,现在产品总数量 {}".
                          format(self.getName(), products))
                    condition.notify()
                else:
                    print("{}:库存充足,让我休息会儿,现在产品总数量 {}".
                          format(self.getName(), products))
                    condition.wait();
                condition.release()
                time.sleep(2)
class Consumer(threading.Thread):
    '''消费者'''
    ix = [0]  # 消费者实例个数
    # 闭包,必须是数组,不能直接 ix = 0
    def __init__(self):
        threading.Thread.__init__(self)
        self.ix[0] += 1
        self.setName('消费者' + str(self.ix[0]))
    def run(self):
        global condition, products
        while True:
            if condition.acquire():
                if products > 1:
                    products -= 1
                    print("{}:我消费了1件产品,现在产品数量 {}".
                          format(self.getName(), products))
                    condition.notify()
                else:
                    print("{}:只剩下1件产品,我停止消费。现在产品数量 {}".
                          format(self.getName(), products))
                    condition.wait();
                condition.release()
                time.sleep(2)
if __name__ == "__main__":
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(10):
        c = Consumer()
        c.start()

  特此记录,学而时习之!

猜你喜欢

转载自www.cnblogs.com/paul010/p/11624902.html