any ways to judge whether an object is initilized or not in a class
James Stroud
jstroud at mbi.ucla.edu
Mon Mar 19 05:16:43 EDT 2007
momobear wrote:
> hi, I am puzzled about how to determine whether an object is
> initilized in one class, anyone could give me any instructions?
> here is an example code:
>
> class coffee:
> def boil(self):
> self.temp = 80
>
> a = coffer()
> if a.temp > 60:
> print "it's boiled"
>
> 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.
>
I think you might be looking for hasattr:
class coffee:
def boil(self):
if hasattr(self, 'temp') and self.temp > 60:
print "Its boilt, yo."
else:
self.temp = 80
Other ways to do this are try/except:
class coffee:
def boil(self):
try:
if self.temp > 60:
print "Its bizzle, yo."
return
except AttributeError:
pass
self.temp = 80
Which is not so good in my opinion because it takes too much typing and
makes your fingers hurt at the very tips.
A fun way is with dict.setdefault which might actually be cleanest, but
you loose testing the precondition for the print:
class coffee:
def boil(self):
if self.__dict__.setdefault('temp', 80) > 60:
print "Its bizzle m'wizzle."
py> c = coffee()
py> c.temp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: coffee instance has no attribute 'temp'
py> c.boil()
Its bizzle m'wizzle.
py> c.temp
80
Of course, the idea is that, in classes, you will be intimately aware of
the attributes of your class via __init__, as others have mentioned, so
you should never really resort to any of the above.
James
More information about the Python-list
mailing list