[Tự Học Python] Các Module Trong Python

🔥CHỌN LỌC TOP NHỮNG KHOÁ HỌC LẬP TRÌNH ONLINE NHIỀU NGƯỜI THEO HOC TẠI ĐÂY🔥

Một module là một file mà chứa các định nghĩa và các câu lệnh Python. Một module có thể định nghĩa ra các hàm, các lớp và các biến. Một module cũng có thể bao gồm thêm các runable code – là những phần code có thể chạy được. Việc gom nhóm những phần code có liên quan với nhau vào trong một module làm cho code của chúng ta dễ hiểu và dễ sử dụng hơn.

Ví dụ:

# ----------------------------------------------------------- #Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam #@author cafedevn #Contact: [email protected] #Fanpage: https://www.facebook.com/cafedevn #Group: https://www.facebook.com/groups/cafedev.vn/ #Instagram: https://instagram.com/cafedevn #Twitter: https://twitter.com/CafedeVn #Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/ #Pinterest: https://www.pinterest.com/cafedevvn/ #YouTube: https://www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/ # ----------------------------------------------------------- # A simple module, calc.py def add(x, y): return (x+y) def subtract(x, y): return (x-y)

1. Câu lệnh import

Chúng ta có thể sử dụng bất kỳ file mã nguồn Python nào làm module cho chương trình của mình bằng cách thực thi một câu lệnh import ở bên trong một số file mã nguồn Python khác.

Khi trình thông dịch (interpreter) gặp một câu lệnh import, nó sẽ nhập cái module đó vào trong chương trình hiện tại nếu module đó có tồn tại bên trong search path – đường dẫn tìm kiếm. Search path là một danh sách các thư mục mà trình thông dịch tìm kiếm trên đó, nhằm nhập vào (importing) một module cụ thể. Ví dụ, để nhập vào module calc.py, chúng ta cần đặt câu lệnh sau đây ở đầu trang code:

# importing module calc.py import calc print add(10, 2)

Kết quả in ra là:

12

2. Cặp câu lệnh from và import

Câu lệnh from của Python cho phép chúng ta nhập vào các thuộc tính cụ thể từ một module. Cặp câu lệnh from … import …. có cú pháp như sau:

# importing sqrt() and factorial from the # module math from math import sqrt, factorial # if we simply do "import math", then # math.sqrt(16) and math.factorial() # are required. print sqrt(16) print factorial(6)

– Kết quả in ra là:

4.0 720

3. Hàm dir()

Hàm dir() được tích hợp sẵn bên trong Python sẽ trả về một danh sách đã được sắp xếp các chuỗi string mà chứa các tên được định nghĩa bởi một module. Danh sách này chứa các tên của tất cả các module, biến, và hàm được định nghĩa bên trong một module.

# Import built-in module random import random print dir(random)

Kết quả in ra là:

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

Sau đây là đoạn code ví dụ mô tả các built-in modules trong Python:

# ----------------------------------------------------------- #Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam #@author cafedevn #Contact: [email protected] #Fanpage: https://www.facebook.com/cafedevn #Group: https://www.facebook.com/groups/cafedev.vn/ #Instagram: https://instagram.com/cafedevn #Twitter: https://twitter.com/CafedeVn #Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/ #Pinterest: https://www.pinterest.com/cafedevvn/ #YouTube: https://www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/ # ----------------------------------------------------------- # importing built-in module math import math # using square root(sqrt) function contained # in math module print math.sqrt(25) # using pi function contained in math module print math.pi # 2 radians = 114.59 degreees print math.degrees(2) # 60 degrees = 1.04 radians print math.radians(60) # Sine of 2 radians print math.sin(2) # Cosine of 0.5 radians print math.cos(0.5) # Tangent of 0.23 radians print math.tan(0.23) # 1 * 2 * 3 * 4 = 24 print math.factorial(4) # importing built in module random import random # printing random integer between 0 and 5 print random.randint(0, 5) # print random floating point number between 0 and 1 print random.random() # random number between 0 and 100 print random.random() * 100 List = [1, 4, True, 800, "python", 27, "hello"] # using choice function in random module for choosing # a random element from a set such as a list print random.choice(List) # importing built in module datetime import datetime from datetime import date import time # Returns the number of seconds since the # Unix Epoch, January 1st 1970 print time.time() # Converts a number of seconds to a date object print date.fromtimestamp(454554)

Kết quả in ra là:

5.0 3.14159265359 114.591559026 1.0471975512 0.909297426826 0.87758256189 0.234143362351 24 3 0.401533172951 88.4917616788 True 1461425771.87 1970-01-06

Nguồn và Tài liệu tiếng anh tham khảo:

  • w3school
  • python.org
  • geeksforgeeks

Tài liệu từ cafedev:

  • Full series tự học Python từ cơ bản tới nâng cao tại đây nha.
  • Ebook về python tại đây.
  • Các series tự học lập trình khác

Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:

  • Group Facebook
  • Fanpage
  • Youtube
  • Instagram
  • Twitter
  • Linkedin
  • Pinterest
  • Trang chủ

Chào thân ái và quyết thắng!

Đăng ký kênh youtube để ủng hộ Cafedev nha các bạn, Thanks you!

Từ khóa » Câu Lệnh Import Trong Python