By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,922 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,922 IT Pros & Developers. It's quick & easy.

Overloading "if object" unary operator

P: n/a
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

Nov 29 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Sarcastic Zombie wrote:
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.

--
Roberto Bonvallet
Nov 29 '06 #2

P: n/a
Sarcastic Zombie wrote:
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
Nov 29 '06 #3

P: n/a


On Nov 29, 11:26 am, Peter Otten <__pete...@web.dewrote:
Sarcastic Zombie wrote:
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
Thanks to both of you, it worked perfectly. I must have missed it in
the documentation somehow.

-Jason Ledbetter

Nov 29 '06 #4

P: n/a
Sarcastic Zombie wrote:
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?
http://effbot.org/pyref/__nonzero__

</F>

Nov 29 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.