Python class default parameter

I was wondering if anyone could explain why these two examples end up giving 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 ... no,” but I am struggling with a second example. Are both suitable for use?

I understand that this can be a pretty simple question, so if someone can direct me to a reading that will help me understand the difference, that will be big.

Thanks!

+5
source share
2 answers

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

  • None

  • False

  • zero of any number 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 method other than zero () or len () when this method returns the integer 0 or bool is False.

So, the first code fragment is more strict. Formal documents, please contact:

+2
source

In the first example, the condition will be true only if parameter literally None .

In the second example, the condition will be true only for the right values.

The simplest way to show this:

 def meth1 (parameter): return parameter is None def meth2 (parameter): return not(bool(parameter)) print([(meth1(v), meth2(v)) for v in [False, None, 0]]) > [(False, True), (True, True), (False, True)] 
+1
source

Source: https://habr.com/ru/post/1266884/


All Articles