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

往函数中传其他类实例的这种操作规范吗?

  •  
  •   tcitry ·
    tcitry · Jun 19, 2017 · 2369 views
    This topic created in 3411 days ago, the information mentioned may be changed or developed.

    比如 Django 中要修改个数据 model 的删除状态。

    def delete_instance(model_obj):
        model_obj.deleted = True
    

    类似这种写法,model_obj 当然是 Django 中一个 models.Model 的类实例。 我的意见是肯定不能这么写,一来不安全,这个 model_obj 可以进行 model 的所有操作。二来在其他地方调用的时候还需要先 get 到这个 model_obj,复用贼麻烦。但还是说不过同事,哎。

    6 replies  •  2017-06-19 18:42:11 +08:00
    kanchi240
        1
    kanchi240  
       Jun 19, 2017
    如果不这么弄,函数参数太多怎么办,楼主给个解决方案
    pixstone
        2
    pixstone  
       Jun 19, 2017
    def delete_instance(model_obj): 这个方法直接写在 model 里。
    Book.delete_instance(id) ???
    tcitry
        3
    tcitry  
    OP
       Jun 19, 2017
    @kanchi240 **kwargs
    kanchi240
        4
    kanchi240  
       Jun 19, 2017
    @tcitry 哦,那又不想用**kwargs 呢,就是想搞的有点面向对象的意思。。
    chairuosen
        5
    chairuosen  
       Jun 19, 2017
    这是写在工具类里,写在对象上的话,如果这个动作要干一些别的事情,就会依赖倒置。
    jswh
        6
    jswh  
       Jun 19, 2017
    这不面向对象
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   972 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 20:23 · PVG 04:23 · LAX 13:23 · JFK 16:23
    ♥ Do have faith in what you're doing.