【问题标题】:How to recognize default method value setting in Python? [duplicate]如何识别 Python 中的默认方法值设置? [复制]
【发布时间】:2020-01-27 17:35:23
【问题描述】:

考虑以下在 Python 中使用默认参数值定义的类方法:

class X
..

    def batch(self, param="foobar", limit=2):
    ...

然后,用户可以不带参数地调用它,就像

x.batch()

结果:参数值被默认值替换。

想象在这种情况下,您想告诉用户这样的事情:

WARNING the batch size has been set to a default value 2.

问题:有没有办法回溯以某种方式拦截以识别它(除了简单地将这个初始化和验证逻辑移动到构造函数方法之外)?

【问题讨论】:

    标签: python methods default-value


    【解决方案1】:

    您无法检测到何时使用默认值,但可能是这样的?

    import warnings
    
    
    class X
    ..
    
        def batch(self, param="foobar", limit=None):
            if limit == None:
                limit = 2
                warnings.warn(...)
    
        ...
    

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 2014-06-08
      • 2019-08-09
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 2013-11-05
      • 2015-12-11
      相关资源
      最近更新 更多