Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class default parameter

Tags:

python

I was wondering if someone could explain why these two examples ultimately yield the same result:

class Myclass(): 

def __init__ (self, parameter=None)

    if parameter is None: 
        self.parameter = 1.0 
    else: 
        self.parameter = parameter

and:

class Myclass():

def __init__ (self, parameter=None)

    if parameter: 
        self.parameter = parameter 
    else: 
        self.parameter = 1.0

I intuitively understand the first 'if... is None' but I struggle with the second example. Are both ok to use?

I realise this could be quite an easy question hence if anyone could direct me to any reading that would help to understand the difference that would be great.

Thanks!

like image 902
Ale Avatar asked Oct 18 '22 13:10

Ale


1 Answers

They are not equivalent, in the first code snippet, parameter will be 1.0 if and only if parameter is None, but in the second one, parameter will be 1.0 for any falsy value.The following values are all falsy in Python:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False.

So the first code snippet is more strict. Official docs please refer to:

  • Python 2: https://docs.python.org/2/library/stdtypes.html#truth-value-testing
  • Python 3: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
like image 162
shizhz Avatar answered Oct 21 '22 08:10

shizhz