[英]Python: Not for Class Instances
In Python, I have the following situation: 在Python中,我有以下情况:
I have an instance of a class named my_class_instance. 我有一个名为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? 什么不not ...
在这种情况下检查? That my_class_instance
is referring to None
? 那my_class_instance
是指None
吗?
The not
operator will call bool
on your instance, then negate the result. not
运算符将在您的实例上调用bool
,然后取反结果。 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
. 因此,如果您的类定义了__bool__
方法,或者从父类继承了__bool__
方法,则该方法将由bool
调用。 It will also call __len__
, if you have one but no __bool__
(empty containers are falsey). 如果您只有一个但没有__bool__
(空容器为false),它也会调用__len__
。 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. 但是,即使您的类实例总是真实的, not my_class_instance
仍然not my_class_instance
。 The test may just be checking if the variable has an actual instance, rather than a falsey placeholder value like None
. 测试可能只是检查变量是否具有实际实例,而不是像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. if my_class_instance is not None
而if not my_class_instance
,则这样的检查应该更明确,并使用它,但是如果您从不期望实际值(而不是None
)永远是假的,以这种方式编写测试并不罕见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.