gpt4 book ai didi

oop - 子类 `pathlib.Path` 失败

转载 作者:行者123 更新时间:2023-12-02 11:06:48 26 4
gpt4 key购买 nike

我想增强类pathlib.Path,但上面的简单示例不起作用。

from pathlib import Path

class PPath(Path):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

test = PPath("dir", "test.txt")

这是我收到的错误消息。

Traceback (most recent call last):
File "/Users/projetmbc/test.py", line 14, in <module>
test = PPath("dir", "test.txt")
File "/anaconda/lib/python3.4/pathlib.py", line 907, in __new__
self = cls._from_parts(args, init=False)
File "/anaconda/lib/python3.4/pathlib.py", line 589, in _from_parts
drv, root, parts = self._parse_args(args)
File "/anaconda/lib/python3.4/pathlib.py", line 582, in _parse_args
return cls._flavour.parse_parts(parts)
AttributeError: type object 'PPath' has no attribute '_flavour'

我做错了什么?

最佳答案

您可以对具体实现进行子类化,这样就可以了:

class Path(type(pathlib.Path())):

这是我对此所做的:

import pathlib

class Path(type(pathlib.Path())):
def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
if encoding is None and 'b' not in mode:
encoding = 'utf-8'
return super().open(mode, buffering, encoding, errors, newline)

Path('/tmp/a.txt').write_text("я")

关于oop - 子类 `pathlib.Path` 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29850801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com