Python 中的面向?qū)ο鬀]有意義

編譯 | 彎月? ?責(zé)編 | 張文
出品 | CSDN(ID:CSDNnews)
許多人都在抨擊面向?qū)ο?,雖然我不認為他有什么問題,但我覺得至少在?Python 中沒必要。
1、沒有必要使用面向?qū)ο?/span>
class ApiClient:
def __init__(self, root_url: str, session_cls: sessionmaker):
self.root_url = root_url
self.session_cls = session_cls
def construct_url(self, entity: str) -> str:
returnf"{self.root_url}/v1/{entity}"
def get_items(self,entity: str) -> List[Item]:
resp = requests.get(self.construct_url(entity))
resp.raise_for_status()
return [Item(**n) for n in resp.json()["items"]]
def save_items(self, entity: str) -> None:
with scoped_session(self.session_cls)as session:
session.add(self.get_items(entity))
class ClientA(ApiClient):
def construct_url(self, entity: str) -> str:
returnf"{self.root_url}/{entity}"
class ClientB(ApiClient):
def construct_url(self, entity: str) -> str:
returnf"{self.root_url}/a/special/place/{entity}"
client_a = ClientA("https://client-a",session_cls)
client_a.save_items("bars")@dataclass
class Client:
root_url: str
url_layout: str
client_a = Client(
root_url="https://client-a",
url_layout="{root_url}/{entity}",
)
client_b = Client(
root_url="https://client-b",
url_layout="{root_url}/a/special/place/{entity}",
)
def construct_url(client: Client, entity: str) -> str:
returnclient.url_layout.format(root_url=client.root_url, entity=entity)
def get_items(client: Client, entity: str) -> List[Item]:
resp = requests.get(construct_url(client, entity))
resp.raise_for_status()
return [Item(**n) for n in resp.json()["items"]]
def save_items(client: Client, session_cls: session_cls, entity: str) -> None:
withscoped_session(session_cls) as session:
session.add(get_items(client, entity))
save_items(client_a,session_cls, "bars")2、例外
你可能注意到,重構(gòu)的代碼中加入了@dataclass,它們只是記錄類型。Python 5 可以直接支持這些,不需要使用“常規(guī)”類。 使用 Exception 的子類是沒問題的。使用 try: ... except SomeClass: ...,基本上會形成一種層級,不過沒關(guān)系,只要不要搞得過于復(fù)雜。 Enum,與上面一樣,它們非常適合 Python。 在極罕見的情況下(至少在應(yīng)用程序的開發(fā)中很少遇到),你可能會想出一種非常好用的類型然后到處使用,就像pandas.DataFrame/sqlalchemy.Session 一樣。但是一般情況下,不要自欺欺人,不要騙自己說我們正在構(gòu)建了不起的應(yīng)用程序。謙虛使人進步。
3、面向?qū)ο蟮谋锥?/span>
面向?qū)ο蠊膭钅阈薷臄?shù)據(jù)。函數(shù)袋非常反對修改參數(shù)。不相信的話,你可以試試看,但可千萬別生氣。 面向?qū)ο笾皇欠祷氐娜肿兞俊D銦o法在函數(shù)之間共享數(shù)據(jù),self 會強迫你使用更小的狀態(tài)空間編寫方便測試的函數(shù)。 混合數(shù)據(jù)和函數(shù)會加劇序列化的難度,而在當(dāng)今 REST API 流行的情況下,序列化非常有用。 面向?qū)ο髱砹睡偪竦睦^承體系,關(guān)于這個話題的討論到處都是。 最重要的是,面向?qū)ο鬀]有任何附加價值,它只會導(dǎo)致你無法專心解決問題,并加劇瀏覽與理解代碼的難度。
推薦閱讀 誤執(zhí)行了rm -fr /*之后,除了跑路還能怎么辦?! 程序員必備58個網(wǎng)站匯總 大幅提高生產(chǎn)力:你需要了解的十大Jupyter Lab插件
評論
圖片
表情
