社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
近来,许多人都在抨击面向对象,虽然我不认为面向对象本身有什么问题,但我觉得至少在 Python 中没这个必要。
1.没有必要使用面向对象
举个例子,比如下面的代码完全没有必要使用面向对象。
- classApiClient:
- def__init__(self, root_url: str, session_cls: sessionmaker):
- self.root_url = root_url
- self.session_cls = session_cls
- defconstruct_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"]]
- defsave_items(self, entity: str) -> None:
- with scoped_session(self.session_cls)as session:
- session.add(self.get_items(entity))
- classClientA(ApiClient):
- defconstruct_url(self, entity: str) -> str:
- returnf"{self.root_url}/{entity}"
- classClientB(ApiClient):
- defconstruct_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")
这里使用了面向对象,因为我们想把 root_url 绑定到某个对象上,而且不想每次都传递 sessionmaker。我们还想使用继承,在调用的中途访问一个方法。但如果只通过数据传递和函数能实现吗?
- @dataclass
- classClient:
- 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}",
- )
- defconstruct_url(client: Client, entity: str) -> str:
- returnclient.url_layout.format(root_url=client.root_url, entityentity=entity)
- defget_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"]]
- defsave_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")
我们必须随时传递 Client 和 session_cls。
但有什么关系呢?代码量甚至还少了 10%。这样编写的代码很容易理解,而且不需要使用面向对象。
有人管这种写法叫做“函数袋”。就是说,整个代码都由有类型的数据和一大堆模块作用域的函数组成。
那么全局变量怎么处理?你可以参考这篇文章(https://leontrolski.github.io/sane-config.html),在整个应用程序的生命周期内重用 config 或 db 的 session,接口、抽象类怎么办?实际上你不需要它们,直接写代码就行了。平心而论,Python 有了类型标注之后,函数袋风格才开始发挥真正的魅力。
不纯粹的函数怎么办?
如果你想采用纯粹的函数式编程,你可能想编写纯粹的类,然后使用不纯粹的“适配器”实例来做一些处理:getting-the-current-datetime/API-calls/talking-to-the-db/other-impure-stuff。这个想法很不错。实际上你可以直接使用 freezegun、responses 等方法来避免大量麻烦。
2. 例外
但也有一些例外的情况:
3. 面向对象的弊端
虽然在本文开头,我说过我不认为面向对象本身有什么问题,但实际上我还是觉得面向对象不仅没有帮助性,而且还常常混淆问题,鼓励一些不良做法:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!