Python 对象应假装为 None 或为空
Python Object should pretend to be None or empty
我有一个具有特定值的 python class。这个 class 只是一个包装器 class,用作另一个 class 对象中的数据容器。
当我在 python 中有任何变量时,我可以通过简单地执行
检查它是否为空(或者就此而言等于 False)
my_variable = "something"
if my_variable
>>> True
my_variable = None # or False, or 0 or whatever equals False
if my_variable
>>> False
到目前为止一切如常。但我希望我的 class 行为完全相同,但前提是某个属性具有特定值,否则它应该 return 为真。这是可能的还是 python 只检查 my_variable
是否绑定到某物?
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
A = Test(True)
B = Test(False)
if A
>>> True
if B
>>> False
听起来您正在为 Python 寻找 __bool__
(or __nonzero__
2).
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
def __bool__(self):
return self.isTrue
我有一个具有特定值的 python class。这个 class 只是一个包装器 class,用作另一个 class 对象中的数据容器。
当我在 python 中有任何变量时,我可以通过简单地执行
检查它是否为空(或者就此而言等于 False)my_variable = "something"
if my_variable
>>> True
my_variable = None # or False, or 0 or whatever equals False
if my_variable
>>> False
到目前为止一切如常。但我希望我的 class 行为完全相同,但前提是某个属性具有特定值,否则它应该 return 为真。这是可能的还是 python 只检查 my_variable
是否绑定到某物?
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
A = Test(True)
B = Test(False)
if A
>>> True
if B
>>> False
听起来您正在为 Python 寻找 __bool__
(or __nonzero__
2).
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
def __bool__(self):
return self.isTrue