Home  >  Article  >  Backend Development  >  How to use python package

How to use python package

王林
王林forward
2023-05-18 13:37:131615browse

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

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

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

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

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

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

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...")

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!"

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!"

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete