Overloading "if object" unary operator

S

Sarcastic Zombie

Good morning,

If I have a class

class A:
__init__(id)
self.id = id

is there any way to overload the 'if' unary usage to detect if a
variable has a value?

For example, in the code:

a = A(56)
if a:
print "Hoo hah!"

how can I insure that the if will come back true and fire off the print
if and only if self.id is defined? I want to do this in an overloaded,
generic way, if possible; I know that I could test for a.id.

Thanks so much!

-Jason Ledbetter
 
R

Roberto Bonvallet

Sarcastic said:
For example, in the code:

a = A(56)
if a:
print "Hoo hah!"

how can I insure that the if will come back true and fire off the print
if and only if self.id is defined? I want to do this in an overloaded,
generic way, if possible; I know that I could test for a.id.

Define a method called __nonzero__ that returns True or False.
 
P

Peter Otten

Sarcastic said:
is there any way to overload the 'if' unary usage to detect if a
variable has a value?

Define a __nonzero__() or __len__() method.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top