Python---Referencing functions in other PY files

Source: Internet
Author: User

There are two ways to implement it, the first one has 2 small methods, the 2nd one is more formal add __init.py__

Description
Create a new file in the directory where you want to reference the file and the PY directory you want to execute: __init.py__, which you can reference by relative path
Method 1
The directory is as follows:

py_test/
├──a
│   ├──a.py
│   └──__init__.py
├──b
│   ├──b.py
│   └──__init __.py
└──__init__.py

a.py content:

# Coding:utf8
def A ():
    print ("I am a")

b.py content:

# Coding:utf8 from
. A import a
a.a ()

Other file is empty
and py_test the same directory, execute the command:

Python-m py_test.b.b

You can call a function in a.py

Method 2
The disadvantage of Method 1 is that you can only execute commands under that path, and if you do not want to use Method 1, you can only encapsulate the code in b.py into a function, create a new c.py under the Py_test folder, and invoke the functions encapsulated in b.py by c.py, which is a more formal approach.
The directory is as follows:

Py_test
├──a
│   ├──a.py
│   └──__init__.py
├──b   │ ├──b.py │ └──__init__. PY
└──c.py

a.py content:

# Coding:utf8

def A ():
    print ("I am a")

b.py content:

# Coding:utf8 from

a.a import a

def b ():
    print ("I am b!")
    A ()

c.py content:

# Coding:utf8 from

b.b import b

B ()

Other files are empty, for example, to execute commands under Py_test:

Python c.py

The sys add path can be performed normally

Description
Add the directory path of the file you want to use to the system path to refer to the
The main forms are as follows:

Import sys
sys.path.append (path)

Use the above form to be aware of using absolute paths, and to note the path differences caused by the operating system

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.