Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียน Python Module เอง (Hello World)

Module = ไฟล์ .py ที่มี Definitions ให้ Import ใช้

1. สร้าง helloworld.py

def hello_world():
    print("Hello world")

2. สร้าง script.py ใช้งาน

import helloworld
helloworld.hello_world()

3. รัน

$ python script.py
Hello world

จัดกลุ่มหลาย Module ด้วย Package


my_package/
    __init__.py      # ทำให้เป็น Package
    core.py
    helpers.py

Import: from my_package import core หรือ import my_package.core

อ่านเพิ่ม: Python Modules Tutorial - Packages, __init__.py, Relative Imports