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

momobear wgwigw at gmail.com
Mon Mar 19 05:28:18 EDT 2007


On Mar 19, 4:50 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> "momobear" <wgw... at gmail.com> wrote:
> > 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.
>
> The simplest thing is simply never to attempt to use a variable or an
> attribute until you know that is has been initialized, so initialize all
> variables before using them, and initialize all attributes in the class's
> __init__ method.
>
> If you don't have a suitable value for the attribute until later then just
> start off with None and then you can check for 'a.boil is not None': if you
> forget to check then Python's strong type checking will stop you from using
> the None value in an expression expecting a number (or a string).
>
> For cases where you aren't sure whether an object has a specific attribute
> you can use getattr with 3 arguments:
>
>    if getattr(a, 'boil', 80):
>        ...
>
> If that isn't convenient (or it's a variable rather than an attribute) you
> should fall back on the principle that 'is it better to ask forgiveness
> than permission': i.e. just try to use the value and handle the exception
> which is thrown if it doesn't exist. (If the fallback is to substitute a
> simple value use getattr, if the fallback is complicated or takes a long
> time to calculate use exception handling).
>
> There is also a function 'hasattr' which will tell you whether or not the
> object has the specified attribute, but internally it just calls 'getattr'
> and handles the exception so (IMHO) it is generally best just not to bother
> with 'hasattr'.

thanks for help:), I am puzzled about if I have to use try and except
to determine it. finnal code should like this?
 class coffee:
         def __init__(self):
              '''
              do something here
              '''
         def  boil(self):
               self.temp = 80

a = coffer()
try:
    if a.temp > 60:
        print "it's boiled"
except AttributeError:
    print "it's not boiled"




More information about the Python-list mailing list