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
NeverBelieveMe
V2EX  ›  Python

类方法要不要设定为静态方法问题

  •  
  •   NeverBelieveMe · 2019-04-15 14:53:40 +08:00 · 1402 次点击
    这是一个创建于 1830 天前的主题,其中的信息可能已经有所发展或是发生改变。
    负责业务处理的 Service 类的方法,比如生成订单 create_order()方法,定义的时候要不要定义成 @staticmethod 静态方法?不设置静态方法,通过 Service().create_order(·······)的方式也可以调用。这样有什么问题么?
    2 条回复    2019-04-17 17:15:45 +08:00
    qiyuey
        1
    qiyuey  
       2019-04-15 15:00:48 +08:00 via Android
    Java 里都是 IOC 的单例 Bean,一般不定义为 Static 的,Python 也应该是类似的吧
    xxx777
        2
    xxx777  
       2019-04-17 17:15:45 +08:00
    ```
    class BaseService:
    model: Model = None
    _service = dict()

    @classmethod
    def instance(cls):
    """Method instance
    :return: cls
    """
    instance = cls._service.get(cls.__name__, None)
    if not instance:
    instance = cls.__new__(cls)
    cls._service.setdefault(cls.__name__, instance)
    return instance
    ```
    可以在基础类写一个 instance 方法,调用的时候 UserService.instance().find_user_by_id() 这样调用是单例
    Service().create_order(·······) 这种每次都会创建新对象的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4047 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:18 · PVG 13:18 · LAX 22:18 · JFK 01:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.