Python Modules And Packages
2023-11-28
筆記如何使用 Python Modules And Packages,讓開發邁向系統與框架化。
Modules
/Models/Person.py
from collections import namedtuple
Person = namedtuple('Person', 'Name, Age, Gender, Pet')
/Models/Pet.py
from collections import namedtuple
Pet = namedtuple('Pet', 'Name, Power')
app.py
import Models.Person as Person
import Models.Pet as Pet
Person('Webber', 26, 'Male', Pet('Pika', 10))
但如果使用 from ... import *
的方式,卻無法成功。原因是因為 from ... import *
引入的是 Modules 當中的 Function, Variable 而不包含 Sub Modules 以及 Class。
為了解決這個問題,可以透過在 Models 加入 __init__.py
,並且在檔案中明確說明如何引用:
/Models/__init__.py
from .Person import Person
from .Pet import Pet
完成後,就可以使用以下方式引用 Modules:
app.py
from Models import *
Person('Webber', 26, 'Male', Pet('Pika', 10))
Packages
my_package/
__init__.py
module1.py
module2.py
setup.py
setup.py
from setuptools import setup, find_packages
setup(
name='my_local_package',
version='0.1',
packages=find_packages(),
install_requires=[
'beautifulsoup4',
'requests',
],
author='Author Name',
author_email='[email protected]',
description='A Python local package with dependencies',
long_description='A Python package that provides useful functionality with dependencies on BeautifulSoup and Requests.',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
)