python变量命名的7条建议

yipeiwu_com7年前Python基础

前言

Quora 问答社区的一个开发者投票统计,程序员最大的难题是:如何命名(例如:给变量,类,函数等等),光是如何命名一项的选票几乎是其它八项的投票结果的总和。如何给变量命名,如何让它变得有意义成了程序员不可逾越的难题,这篇文章参考了 Clean Code ,提供7条命名建议,希望能在取名字的过程中给你带来一些帮助。

以下都是基于Python3.7语法

1、使用有意义而且可读的变量名

差

ymdstr = datetime.date.today().strftime("%y-%m-%d")

鬼知道 ymd 是什么?

好

current_date: str = datetime.date.today().strftime("%y-%m-%d")

看到 current_date,一眼就懂。

2、同类型的变量使用相同的词汇

差 这三个函数都是和用户相关的信息,却使用了三个名字

get_user_info()
get_client_data()
get_customer_record()

好 如果实体相同,你应该统一名字

get_user_info()
get_user_data()
get_user_record()

极好 因为 Python 是一门面向对象的语言,用一个类来实现更加合理,分别用实例属性、property 方法和实例方法来表示。

class User:
  info : str

  @property
  def data(self) -> dict:
    # ...

  def get_record(self) -> Union[Record, None]:
    # ...


3、使用可搜索的名字

大部分时间你都是在读代码而不是写代码,所以我们写的代码可读且可被搜索尤为重要,一个没有名字的变量无法帮助我们理解程序,也伤害了读者,记住:确保可搜索。

差

time.sleep(86400);

What the fuck, 上帝也不知道86400是个什么概念

好

# 在全局命名空间声明变量,一天有多少秒
SECONDS_IN_A_DAY = 60 * 60 * 24

time.sleep(SECONDS_IN_A_DAY)

清晰多了。

4、使用可自我描述的变量

差

address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
matches = re.match(city_zip_code_regex, address)

save_city_zip_code(matches[1], matches[2])

matches[1] 没有自我解释自己是谁的作用

一般

address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$'
matches = re.match(city_zip_code_regex, address)

city, zip_code = matches.groups()
save_city_zip_code(city, zip_code)

你应该看懂了, matches.groups() 自动解包成两个变量,分别是 city,zip_code

好

address = 'One Infinite Loop, Cupertino 95014'
city_zip_code_regex = r'^[^,\\]+[,\\\s]+(?P<city>.+?)\s*(?P<zip_code>\d{5})?$'
matches = re.match(city_zip_code_regex, address)

save_city_zip_code(matches['city'], matches['zip_code'])

5、 不要强迫读者猜测变量的意义,明了胜于晦涩

差

seq = ('Austin', 'New York', 'San Francisco')

for item in seq:
  do_stuff()
  do_some_other_stuff()
  # ...
  # Wait, what's `item` for again?
  dispatch(item)

seq 是什么?序列?什么序列呢?没人知道,只能继续往下看才知道。

好

locations = ('Austin', 'New York', 'San Francisco')

for location in locations:
  do_stuff()
  do_some_other_stuff()
  # ...
  dispatch(location)

用 locations 表示,一看就知道这是几个地区组成的元组

6、不要添加无谓的上下文

如果你的类名已经可以告诉了你什么,就不要在重复对变量名进行描述

差

class Car:
  car_make: str
  car_model: str
  car_color: str

感觉画蛇添足,如无必要,勿增实体。

好

class Car:
  make: str
  model: str
  color: str

7、使用默认参数代替短路运算和条件运算

差

def create_micro_brewery(name):
  name = "Hipster Brew Co." if name is None else name
  slug = hashlib.sha1(name.encode()).hexdigest()
  # etc.

好

def create_micro_brewery(name: str = "Hipster Brew Co."):
  slug = hashlib.sha1(name.encode()).hexdigest()
  # etc.

这个应该能理解吧,既然函数里面需要对没有参数的变量做处理,为啥不在定义的时候指定它呢?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python求最大连续子数组的和

抛出问题: 求一数组如 l = [0, 1, 2, 3, -4, 5, -6],求该数组的最大连续子数组的和 如结果为[0,1,2,3,-4,5] 的和为7 问题分析: 这个问题很...

python实现向微信用户发送每日一句 python实现微信聊天机器人

分享几个Python针对微信的小工具,供大家参考,具体内容如下 用Python实现向微信用户发送每日一句 # -*- coding:utf-8 -*- from __future__...

Python中return self的用法详解

在Python中,有些开源项目中的方法返回结果为self. 对于不熟悉这种用法的读者来说,这无疑使人困扰,本文的目的就是给出这种语法的一个解释,并且给出几个例子。 在Python中,re...

python针对excel的操作技巧

一. openpyxl读 95%的时间使用的是这个模块,目前excel处理的模块,只有这个还在维护 1、workBook workBook=openpyxl.load_workboo...

Django ORM 练习题及答案

1.modles中表结构 #出版社 class Publisher(models.Model): name = models.CharField(max_length=32)...