How to use python package

王林
Release: 2023-05-18 13:37:13
forward
1665 people have browsed it

Detailed instructions for importing and using the module function class definition of the python package

The following is a detailed case of using the Python package, which involves the definition, import and use of modules, functions and classes:

First, we create a directory named my_package as the root directory of the package. Create the following file in it:

my_package/
    __init__.py
    module1.py
    module2.py
Copy after login

In module1.py we define a function called hello():

# my_package/module1.py
def hello():
    print("Hello from module 1!")
Copy after login

In module2.py, we define a class named MyClass:

# my_package/module2.py
class MyClass:
    def __init__(self):
        print("Hello from MyClass!")
Copy after login

Next, in the __init__.py file , we import these modules into the package:

# my_package/__init__.py
from .module1 import hello
from .module2 import MyClass
Copy after login

In addition, we can also add other metadata or initialization code in __init__.py, for example:

# my_package/__init__.py
VERSION = '1.0.0'
print("Initializing my_package...")
Copy after login

Now, we can import and use the package in another Python file:

import my_package
# 调用函数
my_package.hello()       # 输出 "Hello from module 1!"
# 创建类实例
obj = my_package.MyClass()
# 输出 "Hello from MyClass!"
Copy after login

If we only want to import a specific module or symbol, we can use the following syntax:

from my_package.module1 import hello
hello()   # 输出 "Hello from module 1!"
Copy after login

The above is the detailed content of How to use python package. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!