美文网首页
命名的艺术

命名的艺术

作者: _Cappuccino_ | 来源:发表于2020-02-04 09:10 被阅读0次

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.

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


郑重声明

我不是知识的生产者,只是知识的学习者,搬运者,分享者,愿你我一起成长。

本文来自:https://foofish.net/python-naming.html

相关文章

网友评论

      本文标题:命名的艺术

      本文链接:https://www.haomeiwen.com/subject/qmglxhtx.html