Python 中的面向?qū)ο鬀](méi)有意義


許多人都在抨擊面向?qū)ο螅m然我不認(rèn)為他有什么問(wèn)題,但我覺(jué)得至少在 Python 中沒(méi)必要。
1、沒(méi)有必要使用面向?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,它們只是記錄類(lèi)型。Python 5 可以直接支持這些,不需要使用“常規(guī)”類(lèi)。 使用 Exception 的子類(lèi)是沒(méi)問(wèn)題的。使用 try: ... except SomeClass: ...,基本上會(huì)形成一種層級(jí),不過(guò)沒(méi)關(guān)系,只要不要搞得過(guò)于復(fù)雜。 Enum,與上面一樣,它們非常適合 Python。 在極罕見(jiàn)的情況下(至少在應(yīng)用程序的開(kāi)發(fā)中很少遇到),你可能會(huì)想出一種非常好用的類(lèi)型然后到處使用,就像pandas.DataFrame/sqlalchemy.Session 一樣。但是一般情況下,不要自欺欺人,不要騙自己說(shuō)我們正在構(gòu)建了不起的應(yīng)用程序。謙虛使人進(jìn)步。
3、面向?qū)ο蟮谋锥?/span>
面向?qū)ο蠊膭?lì)你修改數(shù)據(jù)。函數(shù)袋非常反對(duì)修改參數(shù)。不相信的話,你可以試試看,但可千萬(wàn)別生氣。 面向?qū)ο笾皇欠祷氐娜肿兞俊D銦o(wú)法在函數(shù)之間共享數(shù)據(jù),self 會(huì)強(qiáng)迫你使用更小的狀態(tài)空間編寫(xiě)方便測(cè)試的函數(shù)。 混合數(shù)據(jù)和函數(shù)會(huì)加劇序列化的難度,而在當(dāng)今 REST API 流行的情況下,序列化非常有用。 面向?qū)ο髱?lái)了瘋狂的繼承體系,關(guān)于這個(gè)話題的討論到處都是。 最重要的是,面向?qū)ο鬀](méi)有任何附加價(jià)值,它只會(huì)導(dǎo)致你無(wú)法專心解決問(wèn)題,并加劇瀏覽與理解代碼的難度。
文章轉(zhuǎn)自:Python程序員(版權(quán)歸原作者所有,侵刪)
![]()
評(píng)論
圖片
表情
