Class attribute or argument value

In Python, I found the following open source:

class Wait:

  timeout = 9

  def __init__(self, timeout=None):

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

I am trying to figure out if there are advantages to the code above vs using the default argument value:

class Wait:

   def __init__(self, timeout=9):
     ...
+3
source share
2 answers

You can change the default value as follows:

Wait.timeout = 20

Will mean that if unset, the default will be 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 exploits the fact that Python searches for class attributes if it does not find an instance attribute.

+12
source

Semantically, a class attribute is similar to creating a default timeout part for a class’s public interface. Depending on the documentation, the end user may be prompted to read or possibly change the default value.

, , .

0

All Articles