温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中变量命名规范有哪些

发布时间:2021-06-17 16:16:20 来源:亿速云 阅读:192 作者:Leah 栏目:开发技术

这篇文章给大家介绍python中变量命名规范有哪些,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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中变量命名规范有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI