In practice, we inevitably have to deal with null values, and I'm sure many beginners will write the following code:.
if a is None: do : do the other thing.
Writing it this way looks good, but it can actually be problematic. In general, Python treats the following cases as nulls.
None False 0,0.0,0L '',(),[],{}
One of the special things about None is that it is neither the value 0 nor the null value of some data structure; it is itself a null object. Its type is NoneType and it follows the single
example pattern, that is, all None in the same namespace are essentially the same null-valued object.
>>> id(None) 1795884240 >>> None == 0 False >>> None == '' False >>> a = None >>> id(a) 1795884240 >>> a == None True
The above judgment clearly does not meet our expectations: a==None is True only if a is shown to be assigned to None.
So what should we do about the more generalized None value judgment in Python?
>>> a = '' # Here is an example of an empty string only, the same applies to other null values >>> if a: ... print 'a is not empty' ... else: ... print 'a is a empty string' 'a is a empty string.'
As you can see, the if a judgment approach yields the result we want, so what exactly is the process of if a judgment approach?
if a will first go to call a's __nonzero__() to determine whether a is empty, and return True/False, if an object does not define __nonzero__(), go to call its __len__() to
Make a judgment (here the return value is 0 for null), if an object does not define the above two methods, then the result of if a will always be True
Next, to verify the above statement.
>>>class A(object): ... def __nonzero__(self): ... print 'running on the __nonzero__' ... return True >>>class B(object): ... def __len__(self): ... print 'running on the __len__' ... return False >>> a, b = A(), B() >>>if a: ... print 'Yep' ... else: ... print 'Nop' running on the __nonzero__ Yep >>>if b: ... print 'Yep' ... else: ... print 'Nop' running on the __len__ Nop
Content Extension:
How to determine if a python function returns null
I don't know what you mean by empty here, is it None or ''?
I'll tell you all about DU:
None is a zhi an empty dao object that represents nothing.
And '', a string object, represents an empty string
If the return value is None, you use the if None: judgment
If it returns '', you use if len('') == 0: Judgment
Netflix Share:
You can directly bai put the function into the if after the du as a condition, if it is empty then zhi judgment result dao is false, for example:
def test(): return None if test(): print True else: print False
to this article on the python judgment is empty examples to share the article is introduced to this, more related to python how to determine the empty content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!