Python 的自定义类继承自 str 类的方式? - V2EX
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Richard14

Python 的自定义类继承自 str 类的方式?

  •  
  •   Richard14 Dec 17, 2022 3258 views
    This topic created in 1246 days ago, the information mentioned may be changed or developed.

    想要自己写一个类,简化一下平时常用的读取文件的过程,

    # 也就是把常见的 with open('file.txt', 'r', encoding='utf-8') as f: text = f.read() # 简化成 text = Read('file.txt') 

    但是最近发现涉及到解码的话还是有些不爽,比如 json 读取

    # 目前的写法 dict_ = json.loads(Read('my_dict.json')) # 理想中的写法,除上文调用方式外还应支持类似链式调用的方式 dict_ = Read('my_dict.json') | json.loads 

    感觉实现起来比较困难,如何让一个类普通时候能当做 str 使用,还能覆盖它的魔术方法,使其支持链式调用呢?我试了试 class Read(str)这种定义方式,结果类无法被 json.loads 读取

    9 replies    2022-12-19 10:59:52 +08:00
    Yourshell
        1
    Yourshell  
       Dec 17, 2022 via Android   1
    UserString
    milkpuff
        2
    milkpuff  
       Dec 18, 2022
    t/743574
    之前看过一篇实现了这个竖杠。
    inframe
        3
    inframe  
       Dec 18, 2022
    https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text

    p = Path('my_text_file')
    p.write_text('Text file contents')
    p.read_text()
    'Text file contents'

    单纯文件操作 Pathlib 内置库就够用
    NoAnyLove
        4
    NoAnyLove  
       Dec 18, 2022
    没看懂,为啥不用 json.load?
    Richard14
        5
    Richard14  
    OP
       Dec 18, 2022
    @NoAnyLove 希望能同时支持 json.loads.read()和 read().json.loads 的写法,两者写码时逻辑顺序不同。
    mmnsghgn
        6
    mmnsghgn  
       Dec 18, 2022
    感觉可以,但没必要

    ```python
    import json


    class Read(str):
    def __new__(cls, filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
    # return super(Read, cls).__new__(cls, f.read())
    return Read.__make_str(f.read())

    @classmethod
    def __make_str(cls, value):
    return super(Read, cls).__new__(cls, value)

    def loads_to_json(self):
    return json.loads(self)

    def strip(self, char = " "):
    return Read.__make_str(super().strip(char))

    def replace(self, *args):
    return Read.__make_str(super().replace(*args))


    # use as str
    file_cOntent= Read("file.txt")

    print("file_content: " + file_content.strip())

    print(json.loads(file_content))

    # chaining
    jsOnContent= Read("file.txt").replace("hell0", "hello").loads_to_json()

    print(jsonContent.get("message"))
    ```

    output:

    ```shell

    Downloads python3 v2ex.py
    file_content: {"message" : "hell0, world!"}

    {'message': 'hell0, world!'}
    hello, world!
    ```
    mmnsghgn
        7
    mmnsghgn  
       Dec 18, 2022
    krixaar
        8
    krixaar  
       Dec 19, 2022
    像 requests 那样 r.text r.json()不就挺好的么?
    julyclyde
        9
    julyclyde  
       Dec 19, 2022
    ```
    import json

    class Read():
    def __init__(self, filename):
    super(Read, self).__init__()
    self.filename = filename

    def __str__(self):
    return open(self.filename, "r").read()

    def loads(self):
    return json.loads(self.__str__())

    i = Read("2.json")
    print(type(i))
    print(i)
    print(i.loads())
    ```
    About     Help     Advertise     Blog     API     FAQ     Solana     882 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 43ms UTC 20:27 PVG 04:27 LAX 13:27 JFK 16:27
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86