- Secret Recipes of the Python Ninja
- Cody Jackson
- 733字
- 2021-06-25 22:14:38
There's more...
In addition to knowing about namespaces, there are some other important terms to know about when installing and working with modules:
- https://pypi.python.org/pypi is the primary database for third-party Python packages.
- pip is the primary installer program for third-party modules and, since Python 3.4, has been included by default with Python binary installations.
- A virtual Python environment allows packages to be installed for a particular application's development, rather than being installed system-wide.
- venv has been the primary tool for creating virtual Python environments since Python 3.3. With Python 3.4, it automatically installs pip and setuptools in all virtual environments.
- The following are common terms for Python files: module, package, library, and distribution. While they have distinct definitions (https://packaging.python.org/glossary/), this book will use them interchangeably at times.
The following is part of dice_roller.py, an example of embedded tests from one of the first Python programs this author wrote when first learning Python:
import random def randomNumGen(choice): if choice == 1: #d6 roll die = random.randint(1, 6) elif choice == 2: #d10 roll die = random.randint(1, 10) elif choice == 3: #d100 roll die = random.randint(1, 100) elif choice == 4: #d4 roll die = random.randint(1, 4) elif choice == 5: #d8 roll die = random.randint(1, 8) elif choice == 6: #d12 roll die = random.randint(1, 12) elif choice == 7: #d20 roll die = random.randint(1, 20) else: #simple error message return "Shouldn't be here. Invalid choice" return die if __name__ == "__main__": import sys print(randomNumGen(int(sys.argv[1])))
In this example, we are simply creating a random number generator that simulates rolling different polyhedral dice (commonly used in role-playing games). The random library is imported, then the function defining how the dice rolls are generated is created. For each die roll, the integer provided indicates how many sides the die has. With this method, any number of possible values can be simulated with a single integer input.
The key part of this program is at the end. The part if __name__ == "__main__" tells Python that, if the namespace for the module is main, that is, it is the main program and not imported into another program, then the interpreter should run the code below this line. Otherwise, when imported, only the code above this line is available to the main program. (It's also worth noting that this line is necessary for cross-platform compatibility with Windows.)
When this program is called from the command line, the sys library is imported. Then, the first argument provided to the program is read from the command line and passed into the randomNumGen() function as an argument. The result is printed to the screen. Following are some examples of results from this program:
$ python3 dice_roller.py 1 2 $ python3 dice_roller.py 2 10 $ python3 dice_roller.py 3 63 $ python3 dice_roller.py 4 2 $ python3 dice_roller.py 5 5 $ python3 dice_roller.py 6 6 $ python3 dice_roller.py 7 17 $ python3 dice_roller.py 8 Shouldn't be here. Invalid choice
Configuring a module in this manner is an easy way to allow a user to interface directly with the module on a stand-alone basis. It is also a great way to run tests on the script; the tests are only run when the file is called as a stand-alone, otherwise the tests are ignored. dice_roller_tests.py is the full dice-rolling simulator that this author wrote:
import random #randint def randomNumGen(choice): """Get a random number to simulate a d6, d10, or d100 roll.""" if choice == 1: #d6 roll die = random.randint(1, 6) elif choice == 2: #d10 roll die = random.randint(1, 10) elif choice == 3: #d100 roll die = random.randint(1, 100) elif choice == 4: #d4 roll die = random.randint(1, 4) elif choice == 5: #d8 roll die = random.randint(1, 8) elif choice == 6: #d12 roll die = random.randint(1, 12) elif choice == 7: #d20 roll die = random.randint(1, 20) else: #simple error message return "Shouldn't be here. Invalid choice" return die def multiDie(dice_number, die_type): """Add die rolls together, e.g. 2d6, 4d10, etc.""" #---Initialize variables final_roll = 0 val = 0 while val < dice_number: final_roll += randomNumGen(die_type) val += 1 return final_roll def test(): """Test criteria to show script works.""" _1d6 = multiDie(1,1) #1d6 print("1d6 = ", _1d6, end=' ') _2d6 = multiDie(2,1) #2d6 print("\n2d6 = ", _2d6, end=' ') _3d6 = multiDie(3,1) #3d6 print("\n3d6 = ", _3d6, end=' ') _4d6 = multiDie(4,1) #4d6 print("\n4d6 = ", _4d6, end=' ') _1d10 = multiDie(1,2) #1d10 print("\n1d10 = ", _1d10, end=' ') _2d10 = multiDie(2,2) #2d10 print("\n2d10 = ", _2d10, end=' ') _3d10 = multiDie(2,2) #3d10 print("\n3d10 = ", _3d10, end=' ') _d100 = multiDie(1,3) #d100 print("\n1d100 = ", _d100, end=' ') if __name__ == "__main__": #run test() if calling as a separate program test()
This program builds on the previous random-dice program by allowing multiple dice to be added together. In addition, the test() function only runs when the program is called by itself to provide a sanity check of the code. The test function would probably be better if it wasn't in a function with the rest of the code, as it is still accessible when the module is imported, as shown below:
>>> import dice_roller_tests.py >>> dice_roller_tests.test() 1d6 = 1 2d6 = 8 3d6 = 10 4d6 = 12 1d10 = 5 2d10 = 8 3d10 = 6 1d100 = 26
So, if you have any code you don't want to be accessible when the module is imported, make sure to include it below the line, as it were.
- TypeScript Essentials
- Instant Testing with CasperJS
- C++程序設計(第3版)
- The Android Game Developer's Handbook
- R語言游戲數(shù)據(jù)分析與挖掘
- 從Java到Web程序設計教程
- 玩轉(zhuǎn).NET Micro Framework移植:基于STM32F10x處理器
- Mastering ASP.NET Core 2.0
- Less Web Development Cookbook
- 創(chuàng)新工場講AI課:從知識到實踐
- Java程序設計
- Java 9:Building Robust Modular Applications
- 小學生C++趣味編程從入門到精通
- Python程序設計現(xiàn)代方法
- Thymeleaf 3完全手冊