3

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):
     ...
4
  • They don't do the same thing. Class attributes are shared between instances. Commented May 5, 2012 at 21:46
  • @Avaris when you do self.timeout = 9, in the second example construct, you're setting a class variable/attribute. Commented May 5, 2012 at 21:50
  • 1
    @Ben Where you are doing self.x = ..., you are setting an instance attribute. Commented May 5, 2012 at 21:53
  • 2
    @Ben, no, you're setting an instance attribute. In the second example, Wait.timeout throws an attributeError. In the first, it does not. Commented May 5, 2012 at 21:55

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

No. If the default parameter is meant to be an implementation detail then its name should be preceded by an underscore, as in _timeout=9.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.