[Tutor] question about __init__ in a class

shawn bright nephish at gmail.com
Mon Nov 13 23:26:04 CET 2006


hey thanks, did not think about the possible consequences of the use of a
built in as a variable name.
-sk

On 11/13/06, Andreas Kostyrka <andreas at kostyrka.org> wrote:
>
> * shawn bright <nephish at gmail.com> [061113 19:46]:
> > Hello there all.
> > i have a class that i need to load some class variables depending on
> what is
> > passed to the class, it would either be set up using one variable or
> > another. The values for the class variables would be loaded from a
> database.
> > But how it is looked up depends on how its called. Like this:
> >
> > class Sensor_Object(object):
> >    def __init__(self, id, monitor):
> >        if id:
> >           self.id = id
> >           load values from the database
> >           value1 = somevalue
> >           value2 = someOthervalue
> >        else:
> >           self.monitor = monitor
> >           get some values from database
> >           value1 = somevalue
> >           value2 = someothervalue
> >
> > now i could call it like this:
> >
> > new_monitor = sensor.Sensor('', 'XJ191')
> > or
> > new_monitor = sensor.Sensor('3433', '')
> > to load based on the other variable.
> >
> > i think that this would work, but i was thinking that there must be a
> > cleaner way to do it.
>
> Well, the code is basically ok, but I'd propose the following (it will
> help using the instances):
>
> class Sensor_Object(object):
>     sensid = None
>     monitor = None
>
>     ...
>
> Basically, provide class variables shadowing your "main" instance
> attributes. I've also renamed id to sensid as id is an builtin
> function. (it's legal and ok to use id, but some tools like pylint
> like to complain about that style of shadowing.)
>
> The benefit is easy, in other methods, you can use code like this:
>     if self.sensid is not None:
> instead of the more clumsy
>     if hasattr(self, "sensid"):
>
> Andreas
>
> > any suggestions ?
> >
> > sk
>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061113/3e41d4aa/attachment.html 


More information about the Tutor mailing list