简体   繁体   English

类属性或参数的默认值

[英]Class attribute or argument's default value

I've found the following open source code in Python: 我在Python中发现了以下开源代码:

class Wait:

  timeout = 9

  def __init__(self, timeout=None):

    if timeout is not None:
        self.timeout = timeout
    ...

I'm trying to understand if there are advantages of the code above vs using default argument's value: 我试图理解上面的代码是否有使用默认参数值的优点:

class Wait:

   def __init__(self, timeout=9):
     ...

It's possible to change the default value this way: 可以通过这种方式更改默认值:

Wait.timeout = 20

Will mean that, if unset, the default will be 20. 意味着,如果未设置,默认值为20。

Eg: 例如:

>>> class Wait:
...     timeout = 9
...     def __init__(self, timeout=None):
...         if timeout is not None:
...             self.timeout = timeout
... 
>>> a = Wait()
>>> b = Wait(9)
>>> a.timeout
9
>>> b.timeout
9
>>> Wait.timeout = 20
>>> a.timeout
20
>>> b.timeout
9

This utilises the fact that Python looks for class attributes if it doesn't find an instance attribute. 这利用了Python在没有找到实例属性的情况下查找类属性的事实。

Semantically, a class attribute is like making the default timeout part of the public interface of the class. 从语义上讲,类属性就像使类的公共接口的默认超时部分一样。 Depending on the documentation, an end user may be encouraged to read or possibly change the default. 根据文档,可能鼓励最终用户阅读或可能更改默认值。

Using a default parameter value instead strongly suggests that the particular default value is an implementation detail, not to be fiddled with by end users of the class. 相反,使用默认参数值强烈建议特定的默认值是实现细节,而不是由类的最终用户进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM