日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python一看就很厉害的代码_Python学习教程:怎么写出让人看起来就很舒服的代码?...

發(fā)布時(shí)間:2023/12/10 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python一看就很厉害的代码_Python学习教程:怎么写出让人看起来就很舒服的代码?... 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python學(xué)習(xí)教程:怎么寫出讓人看起來(lái)很優(yōu)雅舒服的代碼?讓人眼前一亮!

很多新手在開始學(xué)一門新的語(yǔ)言的時(shí)候,往往會(huì)忽視一些不應(yīng)該忽視的細(xì)節(jié),比如變量命名和函數(shù)命名以及注釋等一些內(nèi)容的規(guī)范性,久而久之養(yǎng)成了一種習(xí)慣。對(duì)此,我特意收集了一些適合所有學(xué)習(xí) Python 的伙伴,代碼整潔之道,讓你寫出來(lái)的代碼讓人眼前一亮!!!

寫出 Pythonic 代碼

談到規(guī)范首先想到就是 Python 有名的 PEP8 代碼規(guī)范文檔,它定義了編寫Pythonic代碼的最佳實(shí)踐。可以在

https://www.python.org/dev/peps/pep-0008/ 上查看。但是真正去仔細(xì)研究學(xué)習(xí)這些規(guī)范的朋友并不是很多,對(duì)此呢這篇文章摘選一些比較常用的代碼整潔和規(guī)范的技巧和方法,下面讓我們一起來(lái)學(xué)習(xí)吧!

命名

所有的編程語(yǔ)言都有變量、函數(shù)、類等的命名約定,以美之稱的 Python 當(dāng)然更建議使用命名約定。 接下來(lái)就針對(duì)類、函數(shù)、方法等等內(nèi)容進(jìn)行學(xué)習(xí)。

變量和函數(shù)

使用小寫字母命名函數(shù)和變量,并用下劃線分隔單詞,提高代碼可讀性。

變量的聲明

names = "Python" #變量名

namejob_title = "Software Engineer" #帶有下劃線的變量名

populated_countries_list = [] #帶有下劃線的變量名

還應(yīng)該考慮在代碼中使用非 Python 內(nèi)置方法名,如果使用 Python 中內(nèi)置方法名請(qǐng)使用一個(gè)或兩個(gè)下劃線()。

_books = {}# 變量名私有化

__dict = []# 防止python內(nèi)置庫(kù)中的名稱混淆

那如何選擇是用_還是__呢?

如果不希望外部類訪問(wèn)該變量,應(yīng)該使用一個(gè)下劃線(_)作為類的內(nèi)部變量的前綴。如果要定義的私有變量名稱是 Python 中的關(guān)鍵字如 dict 就要使用(__)。

函數(shù)的聲明

def get_data():

pass

def calculate_tax_data():

pass

函數(shù)的聲明和變量一樣也是通過(guò)小寫字母和單下劃線進(jìn)行連接。

當(dāng)然對(duì)于函數(shù)私有化也是和聲明變量類似。

def _get_data():

pass

函數(shù)的開頭使用單下劃線,將其進(jìn)行私有化。對(duì)于使用 Pyton 中的關(guān)鍵字來(lái)進(jìn)行命名的函數(shù)

要使用雙下劃線。

def __path():

pass

除了遵循這些命名規(guī)則之外,使用清晰易懂的變量名和很重要。

函數(shù)名規(guī)范

# Wrong Way

def get_user_info(id):

db = get_db_connection()

user = execute_query_for_user(id)

return user

# Right way

def get_user_by(user_id):

db = get_db_connection()

user = execute_user_query(user_id)

return user

這里,第二個(gè)函數(shù) get_user_by 確保使用相同的參數(shù)來(lái)傳遞變量,從而為函數(shù)提供正確的上下文。 第一個(gè)函數(shù) get_user_info 就不怎么不明確了,因?yàn)閰?shù) id 意味著什么這里我們不能確定,它是用戶 ID,還是用戶付款I(lǐng)D或任何其他 ID? 這種代碼可能會(huì)對(duì)使用你的API的其他開發(fā)人員造成混淆。為了解決這個(gè)問(wèn)題,我在第二個(gè)函數(shù)中更改了兩個(gè)東西; 我更改了函數(shù)名稱以及傳遞的參數(shù)名稱,這使代碼可讀性更高。

作為開發(fā)人員,你有責(zé)任在命名變量和函數(shù)時(shí)仔細(xì)考慮,要寫讓人能夠清晰易懂的代碼。

當(dāng)然也方便自己以后去維護(hù)。

類的命名規(guī)范

類的名稱應(yīng)該像大多數(shù)其他語(yǔ)言一樣使用駝峰大小寫。

class UserInformation:

def get_user(id):

db = get_db_connection()

user = execute_query_for_user(id)

return user

常量的命名規(guī)范

通常應(yīng)該用大寫字母定義常量名稱。

TOTAL = 56

TIMOUT = 6

MAX_OVERFLOW = 7

函數(shù)和方法的參數(shù)

函數(shù)和方法的參數(shù)命名應(yīng)遵循與變量和方法名稱相同的規(guī)則。因?yàn)轭惙椒▽elf作為第一個(gè)關(guān)鍵字參數(shù)。所以在函數(shù)中就不要使用 self 作為關(guān)鍵字作為參數(shù),以免造成混淆。

def calculate_tax(amount, yearly_tax):

passs

class Player:

def get_total_score(self, player_name):

pass

關(guān)于命名大概就強(qiáng)調(diào)這些,下面讓我們看看表達(dá)式和語(yǔ)句中需要的問(wèn)題。

代碼中的表達(dá)式和語(yǔ)句

users = [

{"first_name":"Helen", "age":39},

{"first_name":"Buck", "age":10},

{"first_name":"anni", "age":9}

]

users = sorted(users, key=lambda user: user["first_name"].lower())

這段代碼有什么問(wèn)題?

乍一看并不容易理解這段代碼,尤其是對(duì)于新開發(fā)人員來(lái)說(shuō),因?yàn)?lambdas 的語(yǔ)法很古怪,所以不容易理解。雖然這里使用 lambda 可以節(jié)省行,然而,這并不能保證代碼的正確性和可讀性。同時(shí)這段代碼無(wú)法解決字典缺少鍵出現(xiàn)異常的問(wèn)題。

讓我們使用函數(shù)重寫此代碼,使代碼更具可讀性和正確性; 該函數(shù)將判斷異常情況,編寫起來(lái)要簡(jiǎn)單得多。

users = [

{"first_name":"Helen", "age":39},

{"first_name":"Buck", "age":10},

{"name":"anni", "age":9}

]

def get_user_name(users):

"""Get name of the user in lower case"""

return users["first_name"].lower()

def get_sorted_dictionary(users):

"""Sort the nested dictionary"""

if not isinstance(users, dict):

raise ValueError("Not a correct dictionary")

if not len(users):

raise ValueError("Empty dictionary")

users_by_name = sorted(users, key=get_user_name)

return users_by_name

如你所見,此代碼檢查了所有可能的意外值,并且比起以前的單行代碼更具可讀性。 單行代碼雖然看起來(lái)很酷節(jié)省了行,但是會(huì)給代碼添加很多復(fù)雜性。 但是這并不意味著單行代碼就不好 這里提出的一點(diǎn)是,如果你的單行代碼使代碼變得更難閱讀,那么就請(qǐng)避免使用它,記住寫代碼不是為了炫酷的,尤其在項(xiàng)目組中。

讓我們?cè)倏紤]一個(gè)例子,你試圖讀取 CSV 文件并計(jì)算 CSV 文件處理的行數(shù)。下面的代碼展示使代碼可讀的重要性,以及命名如何在使代碼可讀中發(fā)揮重要作用。

import csv

with open("employee.csv", mode="r") as csv_file:

csv_reader = csv.DictReader(csv_file)

line_count = 0

for row in csv_reader:

if line_count == 0:

print(f'Column names are {", ".join(row)}')

line_count += 1

print(f'{row["name"]} salary: {row["salary"]}'

f'and was born in {row["birthday month"]}.')

line_count += 1

print(f'Processed {line_count} lines.')

將代碼分解為函數(shù)有助于使復(fù)雜的代碼變的易于閱讀和調(diào)試。

這里的代碼在 with 語(yǔ)句中執(zhí)行多項(xiàng)操作。為了提高可讀性,您可以將帶有 process salary 的代碼從 CSV 文件中提取到另一個(gè)函數(shù)中,以降低出錯(cuò)的可能性。

import csv

with open("employee.csv", mode="r") as csv_file:

csv_reader = csv.DictReader(csv_file)

line_count = 0

process_salary(csv_reader)

def process_salary(csv_reader):

"""Process salary of user from csv file."""

for row in csv_reader:

if line_count == 0:

print(f'Column names are {", ".join(row)}')

line_count += 1

print(f'{row["name"]} salary: {row["salary"]}'

f'and was born in {row["birthday month"]}.')

line_count += 1

print(f'Processed {line_count} lines.')

代碼是不是變得容易理解了不少呢。

在這里,創(chuàng)建了一個(gè)幫助函數(shù),而不是在with語(yǔ)句中編寫所有內(nèi)容。這使讀者清楚地了解了函數(shù)的實(shí)際作用。如果想處理一個(gè)特定的異常或者想從CSV文件中讀取更多的數(shù)據(jù),可以進(jìn)一步分解這個(gè)函數(shù),以遵循單一職責(zé)原則,一個(gè)函數(shù)一做一件事,這個(gè)很重要。

return語(yǔ)句的類型盡量一致

如果希望函數(shù)返回一個(gè)值,請(qǐng)確保該函數(shù)的所有執(zhí)行路徑都返回該值。但是,如果期望函數(shù)只是在不返回值的情況下執(zhí)行操作,則 Python 會(huì)隱式返回 None 作為函數(shù)的默認(rèn)值。

先看一個(gè)錯(cuò)誤示范:

def calculate_interest(principle, time rate):

if principle > 0:

return (principle * time * rate) / 100

def calculate_interest(principle, time rate):

if principle < 0:

return

return (principle * time * rate) / 100ChaPTER 1 PyThonIC ThInkIng

正確的示范應(yīng)該是下面這樣

def calculate_interest(principle, time rate):

if principle > 0:

return (principle * time * rate) / 100

else:

return None

def calculate_interest(principle, time rate):

if principle < 0:

return None

return (principle * time * rate) / 100ChaPTER 1 PyThonIC ThInkIng

還是那句話寫易讀的代碼,代碼多寫點(diǎn)沒關(guān)系,可讀性很重要。

使用 isinstance() 方法而不是 type() 進(jìn)行比較

當(dāng)比較兩個(gè)對(duì)象類型時(shí),請(qǐng)考慮使用 isinstance() 而不是 type,因?yàn)?isinstance() 判斷一個(gè)對(duì)象是否為另一個(gè)對(duì)象的子類是 true。考慮這樣一個(gè)場(chǎng)景:如果傳遞的數(shù)據(jù)結(jié)構(gòu)是dict 的子類,比如 orderdict。type() 對(duì)于特定類型的數(shù)據(jù)結(jié)構(gòu)將失敗;然而,isinstance() 可以將其識(shí)別出它是 dict 的子類。

錯(cuò)誤示范

user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}

type(user_ages) == dict:

正確選擇

user_ages = {"Larry": 35, "Jon": 89, "Imli": 12}

if isinstance(user_ages, dict):

比較布爾值

在Python中有多種方法可以比較布爾值。

錯(cuò)誤示范

if is_empty = False

if is_empty == False:

if is_empty is False:

正確示范

is_empty = False

if is_empty

使用文檔字符串

Docstrings可以在 Python 中聲明代碼的功能的。通常在方法,類和模塊的開頭使用。 docstring是該對(duì)象的__doc__特殊屬性。

Python 官方語(yǔ)言建議使用“”三重雙引號(hào)“”來(lái)編寫文檔字符串。 你可以在 PEP8 官方文檔中找到這些實(shí)踐。 下面讓我們簡(jiǎn)要介紹一下在 Python 代碼中編寫 docstrings 的一些最佳實(shí)踐 。

方法中使用docstring

def get_prime_number():

"""Get list of prime numbers between 1 to 100.""""

關(guān)于docstring的格式的寫法,目前存在多種風(fēng)格,但是這幾種風(fēng)格都有一些統(tǒng)一的標(biāo)準(zhǔn)。即使字符串符合一行,也會(huì)使用三重引號(hào)。當(dāng)你想要擴(kuò)展時(shí),這種注釋非常有用。

三重引號(hào)中的字符串前后不應(yīng)有任何空行

使用句點(diǎn)(.)結(jié)束docstring中的語(yǔ)句

類似地,可以應(yīng)用 Python 多行 docstring 規(guī)則來(lái)編寫多行 docstring。在多行上編寫文檔字符串是用更具描述性的方式記錄代碼的一種方法。你可以利用 Python 多行文檔字符串在 Python 代碼中編寫描述性文檔字符串,而不是在每一行上編寫注釋。

多行的docstring

def call_weather_api(url, location):

"""Get the weather of specific location.

Calling weather api to check for weather by using weather api and

location. Make sure you provide city name only, country and county

names won't be accepted and will throw exception if not found the

city name.

:param url:URL of the api to get weather.

:type url: str

:param location:Location of the city to get the weather.

:type location: str

:return: Give the weather information of given location.

:rtype: str"""

說(shuō)一下上面代碼的注意點(diǎn)第一行是函數(shù)或類的簡(jiǎn)要描述

每一行語(yǔ)句的末尾有一個(gè)句號(hào)

文檔字符串中的簡(jiǎn)要描述和摘要之間有一行空白

如果使用 Python3.6 可以使用類型注解對(duì)上面的docstring以及參數(shù)的聲明進(jìn)行修改。

def call_weather_api(url: str, location: str) -> str:

"""Get the weather of specific location.

Calling weather api to check for weather by using weather api and

location. Make sure you provide city name only, country and county

names won't be accepted and will throw exception if not found the

city name.

"""

怎么樣是不是簡(jiǎn)潔了不少,如果使用 Python 代碼中的類型注解,則不需要再編寫參數(shù)信息。

關(guān)于類型注解(type hint)的具體用法可以參考我之前寫的python類型檢測(cè)最終指南--Typing的使用

模塊級(jí)別的docstring

一般在文件的頂部放置一個(gè)模塊級(jí)的 docstring 來(lái)簡(jiǎn)要描述模塊的使用。

這些注釋應(yīng)該放在在導(dǎo)包之前,模塊文檔字符串應(yīng)該表明模塊的使用方法和功能。

如果覺得在使用模塊之前客戶端需要明確地知道方法或類,你還可以簡(jiǎn)要地指定特定方法或類。

"""This module contains all of the network related requests.

This module will check for all the exceptions while making the network

calls and raise exceptions for any unknown exception.

Make sure that when you use this module,

you handle these exceptions in client code as:

NetworkError exception for network calls.

NetworkNotFound exception if network not found.

"""

import urllib3

import json

在為模塊編寫文檔字符串時(shí),應(yīng)考慮執(zhí)行以下操作:對(duì)當(dāng)前模塊寫一個(gè)簡(jiǎn)要的說(shuō)明

如果想指定某些對(duì)讀者有用的模塊,如上面的代碼,還可以添加異常信息,但是注意不要太詳細(xì)。

NetworkError exception for network calls.

NetworkNotFound exception if network not found.將模塊的docstring看作是提供關(guān)于模塊的描述性信息的一種方法,而不需要詳細(xì)討論每個(gè)函數(shù)或類具體操作方法。

類級(jí)別的docstring

類docstring主要用于簡(jiǎn)要描述類的使用及其總體目標(biāo)。 讓我們看一些示例,看看如何編寫類文檔字符串

單行類docstring

class Student:

"""This class handle actions performed by a student."""

def __init__(self):

pass

這個(gè)類有一個(gè)一行的 docstring,它簡(jiǎn)要地討論了學(xué)生類。如前所述,遵守了所以一行docstring 的編碼規(guī)范。

多行類docstring

class Student:

"""Student class information.

This class handle actions performed by a student.

This class provides information about student full name, age,

roll-number and other information.

Usage:

import student

student = student.Student()

student.get_name()

>>> 678998

"""

def __init__(self):

pass

這個(gè)類 docstring 是多行的; 我們寫了很多關(guān)于 Student 類的用法以及如何使用它。

函數(shù)的docstring

函數(shù)文檔字符串可以寫在函數(shù)之后,也可以寫在函數(shù)的頂部。

def is_prime_number(number):

"""Check for prime number.

Check the given number is prime number

or not by checking against all the numbers

less the square root of given number.

:param number:Given number to check for prime

:type number: int

:return: True if number is prime otherwise False.

:rtype: boolean

"""

如果我們使用類型注解對(duì)其進(jìn)一步優(yōu)化。

def is_prime_number(number: int)->bool:

"""Check for prime number.

Check the given number is prime number

or not by checking against all the numbers

less the square root of given number.

"""

結(jié)語(yǔ)

當(dāng)然關(guān)于 Python 中的規(guī)范還有很多很多,建議大家參考 Python 之禪和 Pep8 對(duì)代碼進(jìn)行優(yōu)化,養(yǎng)成編寫 Pythonic 代碼的良好習(xí)慣。

總結(jié)

以上是生活随笔為你收集整理的python一看就很厉害的代码_Python学习教程:怎么写出让人看起来就很舒服的代码?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。