- Secret Recipes of the Python Ninja
- Cody Jackson
- 313字
- 2021-06-25 22:14:38
How it works...
The location of a named assignment within the code determines its namespace visibility. In the preceding example, steps 1-3, if you directly call second_funct() immediately after calling first_funct(), you'll get an error stating second_funct() is not defined. This is true, because globally, the second function doesn't exist; it's nested within the first function and can't be seen outside the first function's scope. Everything within the first function is part of its namespace, just as the value for x within the second function can't be called directly but has to use the second_funct() call to get its value.
In the preceding examples, step 4-7, the math module is imported in its entirety, but it keeps its own namespace. Thus, calling math.sin() provides a result, but calling sin() by itself results in an error.
Then, the math module is imported using a wildcard. This tells the Python interpreter to import all the functions into the main namespace, rather than keeping them within the separate math namespace. This time, when sin() is called by itself, it provides the correct answer.
This demonstrates the point that namespaces are important to keep code separated while allowing the use of the same variables and function names. By using dot-nomenclature, the exact object can be called with no fear of name shadowing causing the wrong result to be provided.
In preceding examples, steps 7-10, using sys.argv() allows Python to parse command-line arguments and places them in a list for use. sys.argv([0]) is always the name of the program taking the arguments, so it can be safely ignored. All other arguments are stored in a list and can, therefore, be accessed by their index value.
Using *args tells Python to accept any number of arguments, allowing the program to accept a varying number of input values. An alternative version, **kwargs, does the same thing but with keyword:value pairs.
- OpenStack Cloud Computing Cookbook(Third Edition)
- DBA攻堅(jiān)指南:左手Oracle,右手MySQL
- 程序設(shè)計(jì)與實(shí)踐(VB.NET)
- 高效微控制器C語(yǔ)言編程
- C#完全自學(xué)教程
- Learning RxJava
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- Flask Web開發(fā)入門、進(jìn)階與實(shí)戰(zhàn)
- Java面向?qū)ο蟪绦蜷_發(fā)及實(shí)戰(zhàn)
- Java Web基礎(chǔ)與實(shí)例教程
- GameMaker Programming By Example
- Nginx Lua開發(fā)實(shí)戰(zhàn)
- Visual Basic程序設(shè)計(jì)習(xí)題與上機(jī)實(shí)踐
- Python Machine Learning Blueprints:Intuitive data projects you can relate to
- 分布式數(shù)據(jù)庫(kù)原理、架構(gòu)與實(shí)踐