CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/公开课/文档/年薪50W+的Python程序员如何写代码/年薪50W+的Python程序员如何写代码.md
Views: 729
年薪50W+的Python程序员如何写代码
为什么要用Python写代码
没有对比就没有伤害
很多互联网和移动互联网企业对开发效率的要求高于对执行效率的要求。
例子1:hello, world
C的版本:
Java的版本:
Python的版本:
例子2:1-100求和
C的版本:
Python的版本:
例子3:创建和初始化数组(列表)
Java的版本:
Python的版本:
例子4:双色球随机选号
Java的版本:
Python的版本:
温馨提示:珍爱生命,远离任何形式的赌博。
例子5:实现一个简单的HTTP服务器。
Java的版本:
说明:JDK 1.6以前,需要通过套接字编程来实现,具体又可以分为多线程和NIO两种做法。JDK 1.6以后,可以使用
com.sun.net.httpserver
包提供的HttpServer
类来实现。
Python的版本:
或
一行Python代码可以做什么
很多时候,你的问题只需一行Python代码就能解决。
设计模式从未如此简单
Python是动态类型语言,大量的设计模式在Python中被简化或弱化。
思考:如何优化下面的代码。
代理模式在Python中可以通过内置的或自定义的装饰器来实现。
说明:通过Python标准库
functools
模块的lru_cache
装饰器为fib
函数加上缓存代理,缓存函数执行的中间结果,优化代码的性能。
单例模式在Python中可以通过自定义的装饰器或元类来实现。
说明:需要实现单例模式的类只需要添加上面的装饰器即可。
原型模式在Python中可以通过元类来实现。
说明:通过元类给指定了
metaclass=PrototypeMeta
的类添加一个clone
方法实现对象克隆,利用Python标准库copy
模块的copy
和deepcopy
分别实现浅拷贝和深拷贝。
数据采集和数据分析从未如此简单
网络数据采集是Python最擅长的领域之一。
例子:获取豆瓣电影“Top250”。
利用NumPy、Pandas、Matplotlib可以轻松实现数据分析和可视化。
写出Python代码的正确姿势
用Python写代码就要写出Pythonic的代码。
姿势1:选择结构的正确姿势
跨界开发者的代码:
Pythonic的代码:
姿势2:交换两个变量的正确姿势
跨界开发者的代码:
或
Pythonic的代码:
姿势3:用序列组装字符串的正确姿势
跨界开发者的代码:
Pythonic的代码:
姿势4:遍历列表的正确姿势
跨界开发者的代码:
Pythonic的代码:
姿势5:创建列表的正确姿势
跨界开发者的代码:
Pythonic的代码:
姿势6:确保代码健壮性的正确姿势
跨界开发者的代码:
Pythonic的代码:
使用Lint工具检查你的代码规范
阅读下面的代码,看看你能看出哪些地方是有毛病的或者说不符合Python的编程规范的。
PyLint的安装和使用
Pylint是Python代码分析工具,它分析Python代码中的错误,查找不符合代码风格标准(默认使用的代码风格是 PEP 8)和有潜在问题的代码。
Pylint输出格式如下所示。
模块名:行号:列号: 消息类型 消息
消息类型有以下几种:
C - 惯例:违反了Python编程惯例(PEP 8)的代码。
R - 重构:写得比较糟糕需要重构的代码。
W - 警告:代码中存在的不影响代码运行的问题。
E - 错误:代码中存在的影响代码运行的错误。
F - 致命错误:导致Pylint无法继续运行的错误。
Pylint命令的常用参数:
--disable=<msg ids>
或-d <msg ids>
:禁用指定类型的消息。--errors-only
或-E
:只显示错误。--rcfile=<file>
:指定配置文件。--list-msgs
:列出Pylint的消息清单。--generate-rcfile
:生成配置文件的样例。--reports=<y_or_n>
或-r <y_or_n>
:是否生成检查报告。
使用Profile工具剖析你的代码性能
cProfile模块
example01.py
执行结果:
####line_profiler
给需要剖析时间性能的函数加上一个profile
装饰器,这个函数每行代码的执行次数和时间都会被剖析。
example02.py
安装和使用line_profiler
三方库。
####memory_profiler
给需要剖析内存性能的函数加上一个profile
装饰器,这个函数每行代码的内存使用情况都会被剖析。
example03.py
安装和使用memory_profiler
三方库。
如何构建综合职业素养
学习总结
了解全局
确定范围
定义目标
寻找资源
创建学习计划
筛选资源
开始学习,浅尝辄止(YAGNI)
动手操作,边学边玩
全面掌握,学以致用
乐为人师,融会贯通
时间管理
提升专注力
充分利用碎片时间
使用番茄工作法
时间是怎么浪费掉的
任何行动都比不采取行动好
好书推荐
职业规划:《软技能 - 代码之外的生存指南》
吴军系列:《浪潮之巅》、《硅谷之谜》、《数学之美》、……
时间管理:《成为一个更高效的人》、《番茄工作法图解》