我通常使用“不是无”来测试对象是否为空。我看到代码只使用'if object'。它们是一样的吗?
例如,
if Dog:
...
Run Code Online (Sandbox Code Playgroud)
VS
if Dog is not None:
...
Run Code Online (Sandbox Code Playgroud)
语法if Dog调用类的__bool__(或__len__)魔术方法Dog来获取其布尔表示。
一些模块实现了它们的对象的__bool__方法,这样如果调用它就会引发异常,例如pandas:
ValueError: The truth value of a Series is ambiguous...
Run Code Online (Sandbox Code Playgroud)
尽管默认情况下,True如果这些魔术方法都没有实现,则对象将返回。大多数内置函数都实现了__bool__or__len__魔术方法,因此在if语句中使用它们是正常的。
所以对于 alist你可以这样做:
my_list = []
if my_list:
print("List has objects in it") # This will not be called with this code.
Run Code Online (Sandbox Code Playgroud)
默认情况下,类将返回True:
class Foo():
# Classes do this by default
# def __bool__(self):
# return True
pass
f = Foo()
if f:
print("This variable references an object") # This will be called
Run Code Online (Sandbox Code Playgroud)
你可以用这样的方式实现你的类,python 可以更好地理解什么被认为是 Truthy,什么被认为是 Falsey:
class Foo():
def __init__(self):
self.my_list = []
def append(self, ele):
self.my_list.append(ele)
# I could implement this instead of `len`
# def __bool__(self):
# # Some object will raise an exception here
# return bool(self.my_list)
def __len__(self):
return len(self.my_list) > 1
f = Foo()
print("True") if f else print("False") # False
f.append(2)
print("True") if f else print("False") # False
f.append(2)
print("True") if f else print("False") # True
Run Code Online (Sandbox Code Playgroud)
要阅读更多信息,请参阅真值测试