any ways to judge whether an object is initilized or not in a class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 19 10:05:46 EDT 2007


En Mon, 19 Mar 2007 05:35:00 -0300, momobear <wgwigw at gmail.com> escribió:

>> > in C++ language we must initilized a variable first, so there is no
>> > such problem, but in python if we don't invoke a.boil(), we will not
>> > get self.temp to be initilized, any way to determine if it's initilzed
>> > before self.temp be used.
>
> sorry, I should add more code to implement my ideas.
> class coffee:
>          def __init__(self):
>               '''
>               do something here
>               '''
>          def  boil(self):
>                self.temp = 80
>
> a = coffer()
> if a.temp > 60:
>      print "it's boiled"

Apart from the other suggestions (ensure full initialization in __init__,  
using getattr, using hasattr) you may consider using a class attribute as  
a default value:

class Coffee:

     temp = 50

     def __init__(self):
         "do something"

     def  boil(self):
         self.temp = 80

a = Coffee()
print a.temp # 40
a.boil()
print a.temp # 80

-- 
Gabriel Genellina




More information about the Python-list mailing list