Dashuang Python tutorial 8-1 import ` import`

Teaching plan of open course for introduction to Dashuang Python Click to view the tutorial directory

1. Import other file codes

If a function, class, or variable is defined in a py file.
If you want to use it directly in another py file, you can import it using the import statement.

For example, A1 Py is as follows

def check_all_even(nums):
    # Check if they are all even numbers
    for num in nums:
        if num % 2 == 1:
            return False

    return True

a1. Py has the same level file B1 Py (a1.py and b1.py are in the same folder)
b1. Want to use check in py_ all_ Even this function has the following calling methods.

  1. import ...
import a1
a1.check_all_even([1, 2, 3])

This is to import the a1 file and use all the things (functions, classes, variables) in the a1 file,
Use a1 Only the beginning, indicating that the method of a1 is used. (this can help distinguish when there are many imports)

  1. from ... import ...
from a1 import check_all_even
check_all_even([1, 2, 3])

This is a special import of check from the a1 file_ all_ Even method
You can call check directly later_ all_ Even, don't use a1 at the beginning

2 detailed syntax

Suppose there is a file a_long_name_file.py, there are many methods and classes in it,
Like this.

def check_all_even(nums):
    # Check if they are all even numbers
    for num in nums:
        if num % 2 == 1:
            return False

    return True

def check_all_odd(nums):
    # Check if they are all odd
    for num in nums:
        if num % 2 == 0:
            return False

    return True

class Node:
    def __init__(self, num):
        self.num = num
        self.next = None

class AdvancedNode(Node):
    def __init__(self, num):
        super().__init__(num)
        self.prev = None

Method 1

If you use method 1 above

import a_long_name_file

a_long_name_file.check_all_odd([1,2,3])

Write a long a before each method call_ long_ name_ file. Not only hard,
And unsightly (poor readability)

At this time, you can generally use as syntax to give an alias (equivalent to a nickname).
This alias can be used when calling the things inside later.
such as

import a_long_name_file as aln

aln.check_all_odd([1,2,3])

Method 2

If you use the above method 2, you need to import all the functions and classes

from a_long_name_file import check_all_even, check_all_odd, Node, AdvancedNode

check_all_odd([1,2,3])

The price comparison is troublesome and unsightly (poor readability). It needs to be modified in the future.

You can use * here to represent all

from a_long_name_file import *

check_all_odd([1,2,3])

This is a_ long_ name_ Import everything in file

Method 2 supplement

from a_long_name_file import check_all_even

check_all_odd([1,2,3])

If you think check_ all_ If the even name is too long, you can also use as syntax to alias it

from a_long_name_file import check_all_even as check

check([1,2,3])

Here is the check_ all_ The even command is check. You can use check directly later

In general, as can be used to rename variables.

3 __name__=="__main__"

Import details

When importing a file (regardless of the import method used),
The file code is also executed.
For example, B1 Py is as follows

def show_first(word):
    print(word[0])

show_first("abc")

b2. The PY code is as follows

from b1 import show_first

show_first("kind")

b2. The execution output of Py is as follows

a
k

B2 Py first executed B1 Show in PY_ first("abc"),
Then execute its own code show_first("kind").

Test needs

For some supporting code files.
We hope to have some code in it to test its functions or classes.
However, you do not want to execute these test code when importing externally.
Often used__ name__=="__main__"

Examples are as follows

c1.py is as follows

def simple(num):
    line = "-" * num
    print(line)

if __name__ == "__main__":
    simple(2)

The output is as follows

--

c2.py is as follows

import c1

c1.simple(5)

The output is as follows

-----

At this point C2 Py did not execute C1 If of PY__ name__ == "__main__": Code in.

This is exactly what if is__ name__ == "__main__": The role of.
Only when the file itself is run, the if judgment is True and the code under it will be executed.
When a file is imported from another file, if in the file is judged as False, and the code under it will not be executed.

__name__

So__ name__ What the hell is it.
Examples of explanations are as follows

d1. The PY code is as follows

print(__name__)

The execution output is as follows

__main__

d2. The PY code is as follows

import d1

The execution output is as follows

d1

That is, when the file itself is executed__ name__ Will be "_main_",
After being called by other files__ name__ Is its own file name.

Supplement: image__ name__ So the first names are double underlined,
It is a special built-in variable in python.

Added by Mad_T on Tue, 11 Jan 2022 15:22:07 +0200