[Tutor] assert

Kent Johnson kent37 at tds.net
Fri Dec 23 13:56:30 CET 2005


shivayogi kumbar wrote:
> sir,
>    I would like to know about 'asser't keyword how it works in the
> fallowing program

I'm not sure what the question is. Do you not understand assert at all 
or is there something about how this program works that you don't 
understand?

assert is documented here:
http://docs.python.org/ref/assert.html#l2h-461

Simplified a little,
   assert myClass.count>0
is essentially the same as
   if not myClass.count>0: raise AssertionError

assert is usually used to verify an assumption about the state of a 
program at some point. The usage here doesn't really make sense, as 
myClass.count can legitimately be 0. A better assertion would be
   assert myClass.count>=0
since you would expect this to always be true.

Kent

>            class myClass:
>                         count = 0
>                          def __init__(self):
>                                   myClass.count = myClass.count + 1
>                           def __del__(self):
>                                    myClass.count =myClass.count -1
>                                     assert myClass.count>0
>                           def howmany(self):
>                                    return myClass.count
> 
>  >>>a=myClass()
> 
>>>>b=myClass()
>>>>a.howmany()
>>>>del b
>>>>del a
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list