PEP8建议使用简短的变量名,但是要做到这一点需要良好的编程习惯。这里有一些建议可以使变量名简短。
变量名称不是完整的描述符
首先,不要将变量名视为其内容的完整描述符。名称应明确,主要是为了跟踪其来源,然后才可以提供有关内容的一些信息。
# This is very descriptive, but we can infer that by looking at the expressionstudents_with_grades_above_90 = filter(lambda s: s.grade > 90, students)# This is short and still allows the reader to infer what the value wasgood_students = filter(lambda s: s.grade > 90, students)
在评论和文档字符串中添加详细信息
使用注释和文档字符串来描述正在发生的事情,而不是变量名。
# We feel we need a long variable description because the function is not documenteddef get_good_students(students): return filter(lambda s: s.grade > 90, students)students_with_grades_above_90 = get_good_students(students)# If the reader is not sure about what get_good_students returns,# their reflex should be to look at the function docstringdef get_good_students(students): """Return students with grade above 90""" return filter(lambda s: s.grade > 90, students)# You can optionally comment here that good_students are the ones with grade > 90good_students = get_good_students(students)
名称太具体可能意味着代码太具体
如果您觉得某个功能需要一个非常具体的名称,则可能是该功能本身太具体了。
# Very long name because very specific behaviourdef get_students_with_grade_above_90(students): return filter(lambda s: s.grade > 90, students)# Adding a level of abstraction shortens our method name heredef get_students_above(grade, students): return filter(lambda s: s.grade > grade, students)# What we mean here is very clear and the pre is reusablegood_students = get_students_above(90, students)
请注意,在前面的示例中,如何使用
gradeas作为函数自变量可以将其从函数名称中删除,而不会引起任何不清楚。
保持较短的范围以快速查找
将逻辑封装在较短的范围内。这样,您无需在变量名中提供太多详细信息,因为可以在上面几行中快速查找它。一条经验法则是使您的函数适合您的IDE,而无需滚动并在新函数中封装一些逻辑。
# line 6names = ['John', 'Jane']... # Hundreds of lines of pre# line 371# Wait what was names again?if 'Kath' in names: ...
在这里,我失去了对过去的了解
names,向上滚动将使我失去更多的了解。这个更好:
# line 6names = ['John', 'Jane']# I encapsulate part of the logic in another function to keep scope shortx = some_function()y = maybe_a_second_function(x)# line 13# Sure I can lookup names, it is right aboveif 'Kath' in names: ...
花时间思考可读性
最后但并非最不重要的一点是花时间考虑如何使代码更具可读性。这与您花时间思考逻辑和代码优化一样重要。最好的代码是每个人都可以阅读的代码,因此每个人都可以改进。



