天天看點

python __name__

py 檔案直接當腳本運作時:

class Student(object):
    def __init__(self, name,score):

        self.name = name
        self.score = score


    def print_score(self):
        print '%s: %s' % (self.name, self.score -2)
print __name__
if __name__ == "__main__":
    Student('aaa',88).print_score()

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/web/Student.py
__main__
aaa: 86

 if 裡面的語句才會被執行。 這個功能經常可以用于進行測試。

 此時__name__就是__main__

果這個檔案是作為子產品被其他檔案調用,不會執行這裡面的代碼。


from   mycompany.web.Student import *
c=Student('a',98)
c.print_score()

當作子產品使用後:

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
mycompany.web.Student
a: 96

 此時__name__就是mycompany.web.Student