Python 中具体类的抽象类

问题描述 投票:0回答:1

随着 Python 3.12 的发布,

pathlib.Path
现在可以进行子类化。我想为非
CustomPath(Path)
环境(ftp、sftp、s3 存储等)创建一个子类
os
,这意味着我必须重新实现(几乎)所有方法。

我想确保

CustomPath
仅使用子类中定义的方法,以防止意外使用父类
Path
中的方法。为了做到这一点,我只想使用
Path
的接口(抽象类)。 (因为
Path
可能会更新以包含我无法控制的新方法。)

最Python化的方法是什么? (可能情况是根本不适合子类化。)


这是预期行为的示例:

class S3Path(pathlib.Path):
    @classmethod
    def from_connection(cls, ...):
        ...  # custom implementation

    def read_text(self, encoding=None, errors=None):
        ...  # custom implementation


s3path = S3Path.from_connection(...)

text = s3path.read_text()
s3path.write_text(text)  # should raise NotImplementedError
python abstract-class pathlib
1个回答
0
投票

我可以看到两个选项:

选项 1:通过提供如下所示的空主体来覆盖您想要“隐藏”的父方法:

class MyPath(pathlib.Path):
    def is_dir(self):
        pass

选项 2:由于您不想使用基类的任何方法,因此我建议使用组合而不是继承。它将防止您意外使用父类方法。只需根据pathlib.Path规范和您的要求实现您需要的方法即可。

以下是如何使用组合来实现此目的的示例:

import pathlib

class MyPath:
    def __init__(self, path):
        self._path = path

    def exists(self):
        return 'custom implementation of 'exists'

    ######## any other methods

# Example usage:
my_path = MyPath('/path/to/file')
print(my_path.exists())

© www.soinside.com 2019 - 2024. All rights reserved.