Python entry functions (beginner)

Python entry functions (beginner)

I was born in C#and have written a little C/C++, so I always thought of having something like the Main() function as the entrance to the entire program. However, after searching the entire catalog and finding no clues, he began to make various fiddling.

最后更新 3/12/2024 5:24 AM
Ironyho
预计阅读 7 分钟
分类
Python
标签
.NET C# Python rookie entry function

preface

Recently, I was working on a special project within the group. One of the existing tools was developed in Python. My goal is to optimize the process of this tool. Although I can find the corresponding developer to understand the existing process, then propose an optimization plan based on my research, and finally let TA code and implement it. However, the programmer's psychology makes it necessary to figure out everything for himself, so he began the process of exploration.

I searched the Internet for information, downloaded the PyCharm development tool, and made some environment configurations, so I started working. Since I had never been exposed to the Python language before, I opened the code folder and was confused. I only saw a lot of.py files, and I didn't know where to start. I was born in C#and have written a little C/C++, so I always thought of having something like the Main() function as the entrance to the entire program. However, after searching the entire catalog and finding no clues, he began to make various fiddling.

It should be noted that this article is just a Python rookie's study notes and may not necessarily be correct or complete. Everyone is welcome to correct it. Every time I come into contact with new tools or new languages, I feel an inexplicable joy and am happy to use old knowledge to examine them, so I carry them.

sequential execution

In the Python world, every.py file is a module that can be called by entering the file name in the console. A module is somewhat similar to a batch file (.bat), in which the statements are executed sequentially. This was inconsistent with my original imagination. I always thought that it was the same as C#and other languages, and the file should be organized by classes, but it was not.

First, create a file named Test1.py in the root directory of the D drive. The content is as follows:

print("Test1 First")
print("Test1 Second")

Then, go to the console, switch the directory to the D drive, and launch the Test1.py module. The results are as follows:

D:\>python Test1.py
Test1 First
Test1 Second

Well, good, exactly as expected. Try calling between modules again. Create a Test2.py file in the D drive, and call the Test1.py module in it:

import Test1

print("Test2 First")
print("Test2 Second")

Launch Test2.py in the console and output the results:

D:\>python Test2.py
Test1 First
Test1 Second
Test2 First
Test2 Second

可以理解的是,在 Test2.py 文件中, import Test1 语句在前面,所以在导入 Test1 模块时便执行了其中的语句,因此 Test1 中的输出在前面。 If you put import Test1 after it, the output of Test1 will also appear after it:

print("Test2 First")
print("Test2 Second")

import Test1
D:\>python Test2.py
Test2 First
Test2 Second
Test1 First
Test1 Second

function definition

Can the code in the module be more flexible? In addition to executing it sequentially, it can also be called on demand, just like functions in the C#language. The Print above should be a built-in function. Check the data and find the definition of the function in Pyhton:

def 函数名(参数列表):
    函数体

Give it a try and define a SayHello function in Test1.py:

print("Test1 First")
print("Test1 Second")

def SayHello():
	print("Hello World")

SayHello()
print("Test1 Third")

Output results:

D:\>python Test1.py
Test1 First
Test1 Second
Hello World
Test1 Third

Well, as expected, no problem, executed in order.

If you just define the SayHello() function without calling it, there will be no Hello World output.

Next, try calling functions between modules and modify the Test2.py file:

import Test1

print("Test2 First")
print("Test2 Second")

Test1.SayHello()

The output is as follows:

D:\>python Test2.py
Test1 First
Test1 Second
Hello World
Test1 Third
Test2 First
Test2 Second
Hello World

Haha, yes, yes, the Hello World in the last line is output by the Test1.SayHello() statement in Test2.py As for Hello World in the third line above, it was output by the Test1 module when importing Test1.

__main__

了解了函数的定义及模块间的调用,随之而来的疑惑是,程序\模块 的入口在哪里。

搜索了一下资料,找到了 __name__ 属性。先来测试一段代码,修改 Test1.py 文件:

def SayHello():
	print("Hello World")

def SayBye():
	print("Bye World")


SayHello()

if(__name__=="__main__"):
	print("Main")

SayBye()

Launch Test1.py directly in the console:

D:\>python Test1.py
Hello World
Main
Bye World

嗯,还好理解,按顺序执行的,且满足了 if(__name__=="__main__") 条件,所以输出了 Main

Wait a minute, in another way, try calling Test1.py indirectly through Test2.py, and first modify the Test2.py file:

import Test1

print("Test2 First")
print("Test2 Second")

Then launch the Test2.py file to see the results:

D:\>python Test2.py
Hello World
Bye World
Test2 First
Test2 Second

纳尼,怎么没有输出 Main 呢?嗯,有点意思,找到 菜鸟教程 的解释:

每个模块都有一个 __name__ 属性,当其值是 __main__ 时,表明该模块自身在运行,否则是被引入

这个 __name__ 属性还好理解,模块的保留字段(属性),但是怎么理解这个 __main__ 呢?

这里的 __main__ 可能可以理解为程序的入口函数,模块直接被入口函数调用,则其 __name__ 属性值为 main,否则为 模块文件名

def SayHello():
	print("Hello World")

def SayBye():
	print("Bye World")


SayHello()

if(__name__=="__main__"):
	print("Main")
else:
	print(__name__)

SayBye()
D:\>python Test2.py
Hello World
Test1
Bye World
Test2 First
Test2 Second

summary

This article talks about some basic characteristics of Python modules. The knowledge involved is very superficial and only records the personal learning process.

Every time I come into contact with new tools or new languages, I feel an inexplicable joy and am happy to use old knowledge to examine them, so I carry them.

最后,引用 菜鸟教程 关于 模块 的一些重要解释:

  • In addition to method definitions, modules can also include executable code. This code is generally used to initialize this module.
  • A module will only be imported once, no matter how many times you perform imports. This prevents imported modules from being executed over and over again.
  • Modules can be imported into other modules. Importing a module using import at the top of a module is, of course, just a convention and not a mandatory one.
Keep Exploring

延伸阅读

更多文章
同标签 2/7/2026

Summary of experience in using AOT

From the very beginning of project creation, you should develop a good habit of conducting AOT release testing in a timely manner whenever new features are added or newer syntax is used.

继续阅读