类属性或参数的默认值

leg*_*esh 3 python

我在Python中发现了以下开源代码:

class Wait:

  timeout = 9

  def __init__(self, timeout=None):

    if timeout is not None:
        self.timeout = timeout
    ...
Run Code Online (Sandbox Code Playgroud)

我试图理解上面的代码是否有使用默认参数值的优点:

class Wait:

   def __init__(self, timeout=9):
     ...
Run Code Online (Sandbox Code Playgroud)

Gar*_*tty 12

可以通过这种方式更改默认值:

Wait.timeout = 20
Run Code Online (Sandbox Code Playgroud)

意味着,如果未设置,默认值为20.

例如:

>>> 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
Run Code Online (Sandbox Code Playgroud)

这利用了Python在没有找到实例属性的情况下查找类属性的事实.