Reputation: 403
I have a python class that has certain values. This class is just a wrapper class that is used as a datacontainer inside another class object.
When I have any variable in python, I can check if it is empty (or for that matter equal to False) by simply doing
my_variable = "something"
if my_variable
>>> True
my_variable = None # or False, or 0 or whatever equals False
if my_variable
>>> False
So far this is all as usual. But I'd like to behave my class exactly the same but only if a certain attribute has a certain value, otherwise it should return True. Is this possible or does python only check if my_variable
is bound to something or not?
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
A = Test(True)
B = Test(False)
if A
>>> True
if B
>>> False
Upvotes: 0
Views: 238
Reputation: 13589
Sounds like you are looking for __bool__
(or __nonzero__
for Python 2).
class Test(object):
def __init__(self, isTrue):
self.isTrue = isTrue
def __bool__(self):
return self.isTrue
Upvotes: 3