当前位置: 欣欣网 > 办公

因为有这些Python代码陋习,领导让我重构代码到凌晨2点…

2024-04-08办公

点击蓝字 · 关注我们

大家好,我是Bryce~

在Python编程中,有一些常见的坏习惯可能会影响代码的可读性、性能和维护性。本文将介绍 8个常见的Python坏习惯, 并提供对应的好习惯示例代码 ,让你的代码起飞~~~

1. 不适当地使用全局变量

坏习惯:

count = 0
defincrement():
global count
count += 1
return count

好习惯:

defincrement(count):
return count + 1
count = 0
count = increment(count)

2. 不充分利用列表推导式

坏习惯:

squares = []
for i in range(10):
squares.append(i ** 2)

好习惯:

squares = [i ** 2for i in range(10)]

3. 魔法数值和字符串

坏习惯:

defcalculate_circle_area(radius):
return3.14159 * radius ** 2

好习惯:

PI = 3.14159
defcalculate_circle_area(radius):
return PI * radius ** 2

4. 非pythonic的命名方式

坏习惯:

defcalculate_area_of_rectangle(length, width):
return length * width

好习惯:

defcalculate_rectangle_area(length, width):
return length * width

5. 使用不恰当的异常处理方式

坏习惯:

try:
result = 10 / 0
except:
print("An error occurred")

好习惯:

try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)

6. 不充分利用内置函数

坏习惯:

numbers = [12345]
if len(numbers) > 0:
print("List is not empty")

好习惯:

numbers = [12345]
if numbers:
print("List is not empty")

7. 忽略文档字符串

坏习惯:

defadd(a, b):
return a + b

好习惯:

defadd(a, b):
"""
Add two numbers together.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""


return a + b

8. 长函数和复杂逻辑

坏习惯:

defcomplex_function(input_data):
# 复杂逻辑1
# ...
# 复杂逻辑2
# ...
# 复杂逻辑3
# ...
# 复杂逻辑4
# ...
return result

好习惯:

defsimple_functions(input_data):
result_part1 = process_part1(input_data)
result_part2 = process_part2(result_part1)
result_part3 = process_part3(result_part2)
return result_part3

通过避免这些坏习惯,你的Python代码将变得更加优雅、高效和易于维护。

以上就是本次分享的全部内容。我是Bryce,我们下期见~

你好!我是Bryce,大厂数据分析师,数据模型大赛一等奖获得者,比例1%。连续两年晋升涨薪,目前是某项目数据业务负责人。持续分享数据分析、AI编程、AI办公等文章,我们一起拥抱变化、一起精进。

关注下方公众号,回复【数据分析书籍】,即可获取SQL、Python、机器学习等电子书合集。

关注我

常进步