推荐学习书目
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
Elliota
V2EX  ›  Python

如何在不改动模块的情况下重写其中某一个关键类,且其他依赖关键类的文件能自动调用重构后的类?

  •  
  •   Elliota · Jul 13, 2021 · 2493 views
    This topic created in 1777 days ago, the information mentioned may be changed or developed.

    说的有点抽象,下面用 selenium 模块举个例子。

    remote/webdriver.py文件中有下面一个类,为标题说的关键类。

    class WebDriver(object):
        pass
    

    chrome/webdriver.py文件中,依赖上述关键类,称这个文件为依赖关键类的文件,其内容如下。

    #...
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
    #...
    class WebDriver(RemoteWebDriver):
        pass
    

    现在,我想重写关键类。并且,依赖关键类的文件的文件会自动调用我重写的类,基本要求是不改动模块文件。

    不知列位有没有看懂,我尽力表达了... 各位 v 友,有招嘛,不懂得但是对这个问题有兴趣的可以回一下贴,顶一下,让大佬看到😁,感谢感谢~

    6 replies    2021-07-14 11:51:45 +08:00
    pursuer
        1
    pursuer  
       Jul 13, 2021
    修改 sys.path 或者 sys.meta_path,让 import 优先加载你自己写的 py 文件
    renmu123
        2
    renmu123  
       Jul 13, 2021 via Android   ❤️ 1
    猴子补丁?
    wuwukai007
        3
    wuwukai007  
       Jul 13, 2021
    chrom/__init__.py
    class MyWebDriver:
    pass
    from selenium.webdriver.remote import webdriver
    webdriver.WebDriver = MyWebDriver
    muzuiget
        4
    muzuiget  
       Jul 13, 2021
    就是 monkey patch 大法,很正常的操作。
    lanlanye
        5
    lanlanye  
       Jul 14, 2021
    如果依赖关键类的文件都是你自己写的,改个名字就可以了,否则就按楼上的来
    crclz
        6
    crclz  
       Jul 14, 2021
    在自己的工程中,叫依赖注入。注意子类要能够里氏替换。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6026 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 02:58 · PVG 10:58 · LAX 19:58 · JFK 22:58
    ♥ Do have faith in what you're doing.