any ways to judge whether an object is initilized or not in a class
Duncan Booth
duncan.booth at invalid.invalid
Mon Mar 19 04:50:15 EDT 2007
"momobear" <wgwigw 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'.
More information about the Python-list
mailing list