推荐学习书目
› 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 · Apr 15, 2019 · 2273 views
    This topic created in 2731 days ago, the information mentioned may be changed or developed.
    负责业务处理的 Service 类的方法,比如生成订单 create_order()方法,定义的时候要不要定义成 @staticmethod 静态方法?不设置静态方法,通过 Service().create_order(·······)的方式也可以调用。这样有什么问题么?
    2 replies  •  2019-04-17 17:15:45 +08:00
    qiyuey
        1
    qiyuey  
       Apr 15, 2019 via Android
    Java 里都是 IOC 的单例 Bean,一般不定义为 Static 的,Python 也应该是类似的吧
    xxx777
        2
    xxx777  
       Apr 17, 2019
    ```
    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(·······) 这种每次都会创建新对象的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1101 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:18 · PVG 01:18 · LAX 10:18 · JFK 13:18
    ♥ Do have faith in what you're doing.