总结的几个Python函数方法设计原则
在任何编程语言中,函数的应用主要出于以下两种情况:
1.代码块重复,这时候必须考虑用到函数,降低程序的冗余度
2.代码块复杂,这时候可以考虑用到函数,增强程序的可读性
当流程足够繁杂时,就要考虑函数,及如何将函数组合在一起。在Python中做函数设计,主要考虑到函数大小、聚合性、耦合性三个方面,这三者应该归结于规划与设计的范畴。高内聚、低耦合则是任何语言函数设计的总体原则。
1.如何将任务分解成更有针对性的函数从而导致了聚合性
2.如何设计函数间的通信则又涉及到耦合性
3.如何设计函数的大小用以加强其聚合性及降低其耦合性
【聚合】
每个函数只做一件事
完美的程序设计,每个函数应该而且只需做一件事。
比如说:把大象放进冰箱分三步:把门打开、把大象放进去、把门关上。
这样就应该写三个函数而不是一个函数拿所有的事全做了。这样结构清晰,层次分明,也好理解!
【大小】
保持简单、保持简短
Python即是面向过程的语言,也是面向对象的语言,但更多的是充当脚本语言的角色。
同样的功能,使用Python来实现其代码长度也许是C/C++/Java等语言的1/3. 几百行代码就能实现不小的功能!
如果项目中设计的一个函数需要翻页才能看完的话,就要考虑将函数拆分了。
在Python自带的200多个模块中,很少看到某个函数有两、三页的。
Python代码以简单明了著称,一个过长或者有着深层嵌套的函数往往成为设计缺陷的征兆。
【耦合】
输入使用参数、输出使用return语句
这样做可以让函数独立于它外部的东西。参数和return语句就是隔离外部依赖的最好的办法。
慎用全局变量
第一重考虑: 全局变量通常是一种蹩脚的函数间的进行通信的方式。
它会引发依赖关系和计时的问题,从而会导致程序调试和修改的困难。
第二重考虑: 从代码及性能优化来考虑,本地变量远比全局变量快。
根据Python对变量的搜索的先后顺序: 本地函数变量==》上层函数变量==》全局变量==》内置变量
从上面可以看出,本地变量优先被搜索,一旦找到,就此停下。下面专门对其做了测试,测试结果如下:
import profile A = 5 def param_test(): B = 5 res = 0 for i in range(100000000): res = B + i return res if __name__=='__main__': profile.run('param_test()') >>> ===================================== RESTART ===================================== >>> 5 function calls in 37.012 seconds #全局变量测试结果:37 秒 Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 19.586 19.586 19.586 19.586 :0(range) 1 1.358 1.358 1.358 1.358 :0(setprofile) 1 0.004 0.004 35.448 35.448 <string>:1(<module>) 1 15.857 15.857 35.443 35.443 Learn.py:5(param_test) 1 0.206 0.206 37.012 37.012 profile:0(param_test()) 0 0.000 0.000 profile:0(profiler) >>> ===================================== RESTART ===================================== >>> 5 function calls in 11.504 seconds #局部变量测试结果: 11 秒 Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 3.135 3.135 3.135 3.135 :0(range) 1 0.006 0.006 0.006 0.006 :0(setprofile) 1 0.000 0.000 11.497 11.497 <string>:1(<module>) 1 8.362 8.362 11.497 11.497 Learn.py:5(param_test) 1 0.000 0.000 11.504 11.504 profile:0(param_test()) 0 0.000 0.000 profile:0(profiler)
避免改变可变类型参数
Python数据类型比如说列表、字典属于可变对象。在作为参数传递给函数时,有时会像全局变量一样被修改。
这样做的坏处是:增强了函数之间的耦合性,从而导致函数过于特殊和不友好。维护起来也困难。
这个时候就要考虑使用切片S[:]和copy模块中的copy()函数和deepcopy()函数来做个拷贝,避免修改可变对象
具体参考这篇文章: Python中的深浅拷贝详解
避免直接改变另一个模块中的变量
比如说在b.py文件中导入a模块,a中有变量PI = 3.14, 但b.py想将其修改为:PI = 3.14159, 在这里你就搞不清楚变量PI原先的值到底是多少。碰到这种情况,可以考虑用易懂的函数名来实现:
#模块a.py PI = 3.14 def setPi(new): PI = new return PI
这样既有自己想要的PI的值,又没有改变a模块中PI的值
import a PI = a.setPi(3.14159) print PI;a.PI

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
