legesh
legesh

Reputation: 2227

Class attribute or argument's default value

I've found the following open source code in 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):
     ...

Upvotes: 3

Views: 1037

Answers (2)

chepner
chepner

Reputation: 530872

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.

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 88977

It's possible to change the default value this way:

Wait.timeout = 20

Will mean that, if unset, the default will be 20.

E.g:

>>> 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.

Upvotes: 12

Related Questions