Reputation: 1771
Is there something like _if_ or _not_ methods implemented in a customized class? So when I instantiate a new class, I can use
if myobject:
return True
or
if not myobject:
return False
Upvotes: 0
Views: 65
Reputation: 88378
If what you want is to use instances of your class as boolean values, i.e., some of the instances of your class are truthy and some are falsy, then, in your class, define __nonzero__
appropriately.
See Section 5.1 in the docs
By default, saying
if myobject:
where myobject
is an instance of some class, will evaluate as if you wrote
if True:
Defining __nonzero__()
allows you customize how your objects are used in a boolean context (so to speak).
For Python 3, things are a little different. See this SO question.
Upvotes: 3