morfizm (morfizm) wrote,
morfizm
morfizm

Python boolean function danger

class number(int):
    def is_odd(self):
        return self % 2 == 1

>>> if number(5).is_odd(): print '5 is odd'
...
5 is odd

>>> if number(6).is_odd(): print '6 is odd'
...

>>> if number(5).is_odd: print '5 is odd'
...
5 is odd

>>> if number(6).is_odd: print '6 is odd'
...
6 is odd


Upd.: got a good solution. Use properties:

class number(int):
    @property
    def is_odd(self):
        return self % 2 == 1

print number(6).is_odd
print number(6).is_odd()

the latter call will produce
TypeError: 'bool' object is not callable
Tags: software development
Subscribe
  • 24 comments
  • 24 comments

Comments for this post were locked by the author