zoukankan      html  css  js  c++  java
  • Use Module and Function instead of Class in Python

    The following scripts run in ipython demonstrate the differences between instance method and static method. Generally OOP make things complicated for imperative style applications. So when developing this style application (such as command-line application) use functions inside modules, instead of "module - class - method". The Python standard library is a good example that all utility functions are all common functions not wrapped in classes.

    In [1]: cat utils.py
    class FileUtils:
        def __init__(self):
            print 'initialize', self
    
        @staticmethod
        def static_copy(src, dst):
            print 'class copy from', src, 'to', dst
    
        def instance_copy(self, src, dst):
            print self, 'copy from', src, 'to', dst
    
    In [2]: import utils
    
    In [3]: myutil = utils.FileUtils()
    initialize <utils.FileUtils instance at 0x8ab250c>
    
    In [4]: myutil.instance_copy('aa', 'bb')
    <utils.FileUtils instance at 0x8ab250c> copy from aa to bb
    
    In [5]: utils.FileUtils().instance_copy('aa', 'bb')
    initialize <utils.FileUtils instance at 0x8ab24ec>
    <utils.FileUtils instance at 0x8ab24ec> copy from aa to bb
    
    In [6]: utils.FileUtils.static_copy('aa', 'bb')
    class copy from aa to bb
    
    In [7]: utils.FileUtils.instance_copy('aa', 'bb')
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-7-cce9f79fc45b> in <module>()
    ----> 1 utils.FileUtils.instance_copy('aa', 'bb')
    
    TypeError: unbound method instance_copy() must be called with FileUtils instance as first argument (got str instance instead)
    
    In [8]: myutil.static_copy('aa', 'bb')
    class copy from aa to bb
    

    Notice the subtle difference between [5] and [6], parenthesis followed the class name is a "instance", while only class name without the following parenthesis is a "class".

    Ref: The definitive guide on how to use static, class or abstract methods in Python

  • 相关阅读:
    cocos2d-x 3.0 事件分发机制
    cocos2d-x Schedule详解
    OSG设置警告等级
    OSG四元数与欧拉角之间的转换
    编译OSG_FBX插件
    RakNet发送与接收数据
    RakNet基本教程
    IE不能上网,但是其他浏览器可以
    OSG计时器与时间戳
    添加OSG各种事件处理器
  • 原文地址:https://www.cnblogs.com/darkmatter/p/3606853.html
Copyright © 2011-2022 走看看