V2EX = way to explore
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
tcitry
V2EX  ›  Python

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

  •  
  •   tcitry ·
    tcitry · 2017-06-19 11:26:29 +08:00 · 1720 次点击
    这是一个创建于 2493 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    def delete_instance(model_obj):
        model_obj.deleted = True
    

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

    6 条回复    2017-06-19 18:42:11 +08:00
    kanchi240
        1
    kanchi240  
       2017-06-19 13:15:59 +08:00
    如果不这么弄,函数参数太多怎么办,楼主给个解决方案
    pixstone
        2
    pixstone  
       2017-06-19 13:21:34 +08:00
    def delete_instance(model_obj): 这个方法直接写在 model 里。
    Book.delete_instance(id) ???
    tcitry
        3
    tcitry  
    OP
       2017-06-19 14:41:26 +08:00
    @kanchi240 **kwargs
    kanchi240
        4
    kanchi240  
       2017-06-19 18:34:27 +08:00
    @tcitry 哦,那又不想用**kwargs 呢,就是想搞的有点面向对象的意思。。
    chairuosen
        5
    chairuosen  
       2017-06-19 18:40:04 +08:00
    这是写在工具类里,写在对象上的话,如果这个动作要干一些别的事情,就会依赖倒置。
    jswh
        6
    jswh  
       2017-06-19 18:42:11 +08:00
    这不面向对象
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5624 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 05:54 · PVG 13:54 · LAX 22:54 · JFK 01:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.