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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
where
myobjectis an instance of some class, will evaluate as if you wroteDefining
__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.