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!
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With