File tree 1 file changed +25
-1
lines changed 1 file changed +25
-1
lines changed Original file line number Diff line number Diff line change @@ -256,7 +256,7 @@ def fancy_func():
256
256
257
257
所以,请打开 IDE 的智能提示,及时清理掉那些定义了但是没有使用的变量吧。
258
258
259
- ### 7. 能不定义变量就不定义
259
+ ### 7. 不要定义没有意义的变量名字
260
260
261
261
有时候,我们定义变量时的心理活动是这样的:『嗯,这个值未来说不定会修改/二次使用』,让我们先把它定义成变量吧!
262
262
@@ -283,6 +283,30 @@ def get_best_trip_by_user_id(user_id):
283
283
284
284
没有必要为了那些可能出现的变动,牺牲代码当前的可读性。如果以后有定义变量的需求,那就以后再加吧。
285
285
286
+ 但有时候,定义额外的变量名可以增加程序的可读性。为布尔值取名字是人们经常会忽略
287
+ 的做法,比如下面这段代码:
288
+
289
+ ```
290
+ # 如果活动还在开放,并且活动剩余名额大于 10,为所有性别为女性,或者级别大于 3
291
+ # 的活跃用户发放 10000 个金币
292
+ if activity.is_active and activity.remaining > 10 and \
293
+ user.is_active and (user.sex == 'female' or user.level > 3):
294
+ user.add_coins(10000)
295
+ return
296
+ ```
297
+
298
+ 假如我们通过取名字来解释这段代码,甚至没有必要添加注释(当然,更好的方法是将这
299
+ 个逻辑进行封装,见
300
+ [ 2.2封装那些过于复杂的逻辑判断] ( 2-if-else-block-secrets.md#2-封装那些过于复杂的逻辑判断 ) )
301
+
302
+ ```
303
+ activity_is_ongoing = activity.is_active and activity.remaining > 10
304
+ user_is_eligible = user.is_active and (user.sex == 'female' or user.level > 3)
305
+ if activity_is_ongoing and user_is_eligible:
306
+ user.add_coins(10000)
307
+ return
308
+ ```
309
+
286
310
## 结语
287
311
288
312
碎碎念了一大堆,不知道有多少人能够坚持到最后。变量作为程序语言的重要组成部分,值得我们在定义和使用它时,多花一丁点时间思考一下,那样会让你的代码变得更优秀。
You can’t perform that action at this time.
0 commit comments