50个成为优秀程序员的法则[21-30]

原文链接: 50 Coding Laws That Would Make You A Decent Programmer. 21. 避免魔法数字 魔法数字是一个硬编码的值,可能会在稍后阶段更改,但因此很难更新。 1 2 3 4 5 # ❌ SELECT TOP 50 * FROM orders # ✅ NUM_OF_ORDERS = 50 SELECT TOP NUM_OF_ORDERS * FROM orders 22. 避免深度嵌套 1 2 3 4 5 6 7 # ❌ if x: if y: do_something() # ✅ if x and y: do_something() 23. 避免临时变量 1 2 3 4 5 # ❌ temp_result = calculate(x, y) final_result = temp_result * 2 # ✅ final_result = calculate(x, y) * 2 24. 避免使用神秘的缩写 1 2 3 4 5 6 # ❌ def calc(x, y): pass # ✅ def calculate_total_price(quantity, unit_price): pass 25. 避免硬编码Path 1 2 3 4 5 # ❌ file_path = "/path/to/file.txt" # ✅ import os file_path = os.getenv("FILE_PATH") 26. 使用使用Try…Catch…Finally语句 在编写代码时,最好也包括错误处理。这有助于加快调试过程并提高代码的复杂性,同时保持干净和可管理。 ...

October 14, 2024 · Wuxf

50个成为优秀程序员的法则[11-20]

原文链接: 50 Coding Laws That Would Make You A Decent Programmer. 11. 不要成为一个肮脏的程序员 这意味着你要写干净的代码,但什么才是干净的代码呢?干净的代码结构良好,排列良好。干净的代码不会隐藏错误。它向程序员公开了bug可以隐藏的任何地方,并可以无需完全重构就可以修复其中的bug。 ...

June 20, 2024 · Wu Xiangfeng

Python中的bytes对象以及UTF-8编码

看了 `bytes`: The Lesser-Known Python Built-In Sequence • And Understanding UTF-8 Encoding 之后自己尝试了一下中文,加深了对UTF-8的一点点理解. Python的bytes对象 bytes 是由单个字节构成的不可变整数序列。序列中的每个值的大小被限制为 0 <= x < 256 (如果违反此限制将引发 ValueError)。 ...

June 7, 2024 · Wuxf

50个成为优秀程序员的法则[1-10]

原文链接: 50 Coding Laws That Would Make You A Decent Programmer. 1. 不惜一切代价避免注释 开幕暴击,一直以来各种书籍文章或者资料大多建议要写注释,当然我也看到另一种说法不写注释写Wiki,仔细看完作者的观点之后觉得还是挺有道理,作者列举的理由如下: ...

June 5, 2024 · Wuxf

Jupyterlab中显示Plotly的图形

需要借助 IPython.dispaly.HTML 对象,在 Jupyterlab 安装的时候就已经可用了,具体用法如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from IPython.display import HTML import plotly.graph_objects as go # 准备数据 x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] # 创建线形图 fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=y, mode="lines")) fig.update_layout( title="Simple Line Plot", xaxis_title="X", yaxis_title="Y", font=dict(family="Courier New, monospace", size=18, color="#7f7f7f"), ) # 显示图形 HTML(fig.to_html())

June 4, 2024 · Wuxf