About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , You will often encounter many identical or very similar operations , At this time , Code that implements similar operations can be encapsulated as functions , Then call the function where you need it . This can not only realize code reuse , It can also make the code more organized , Increase code reliability . Now let's introduce python Function of __name__ Attribute related content .
original “test_1.py” Add the following test code to the file :
import test_1 # Import test_1 modular
c = test_1.minimal(5,6) # Call function , Assign a smaller value to c
print(' The smaller value is :',c) # Output smaller values c
def minimal(x, y): # Custom calculate small value function
if x > y: # If x>y establish , return y Value
return y
else: # Otherwise return to x Value
return x
# For testing
r = minimal(2,3)
print(' test 2 and 3 The smaller value of is :',r)
example : Run the above program , Analyze the running results .
for example : Want to achieve will “test_1.py” Run directly as a program , Execute test code ; and “test_1.py” When importing as a module , Do not execute test code , Can be “test_1.py” The code in the file is modified as follows :
def minimal(x, y): # Custom calculate small value function
if x > y: # If x>y establish , return y Value
return y
else: # Otherwise return to x Value
return x
# For testing
if __name__ == '__main__': # Identify the current operation mode
r = minimal(2,3)
print(' test 2 and 3 The smaller value of is :',r)
example : Run the following program , Analyze the running results . It can be seen that the printing information in the module file method will not be printed when called .
import test_1 # Import test_1 modular
c = test_1.minimal(5,6) # Call function , Assign a smaller value to c
print(' The smaller value is :',c) # Output smaller values c
def minimal(x, y): # Custom calculate small value function
if x > y: # If x>y establish , return y Value
return y
else: # Otherwise return to x Value
return x
# For testing
r = minimal(2,3)
give the result as follows .
1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial
The above is about Python Function of __name__ Attribute related knowledge , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .