Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Viết module Python

Module là file chứa định nghĩa và statement Python. Tên file là tên module với suffix .py.

Tạo file helloworld.py với hàm sau:

def hello_world():
    print "Hello world"

Tạo file khác cùng thư mục tên script.py với nội dung:

import helloworld
helloworld.hello_world()

Chúng ta tạo module helloworld, import vào script.py, dùng hàm từ helloworld.py. Tạo nhiều module trong working directory gây rối. Dùng package để gom nhóm module gọn gàng. Đọc thêm cách tạo và dùng package: https://docs.python.org/2/tutorial/modules.html#packages