简体   繁体   中英

Python: Not for Class Instances

In Python, I have the following situation:

I have an instance of a class named my_class_instance.

The code does the following check:

if not my_class_instance:
    print ("check was reached")

What does not ... check in this situation? That my_class_instance is referring to None ?

The not operator will call bool on your instance, then negate the result. So if your class has defined a __bool__ method, or if you inherit one from a parent class, then that method will be called by bool . It will also call __len__ , if you have one but no __bool__ (empty containers are falsey). If you don't have one of those methods, your instances will always be truthy.

But even if instances of your class are always truthy, doing not my_class_instance might still make sense. The test may just be checking if the variable has an actual instance, rather than a falsey placeholder value like None . Such a check should probably be more explicit and use if my_class_instance is not None instead of if not my_class_instance , but it's not uncommon to write the test that way if you never expect an actual value (rather than None ) to ever be falsey.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM