[Tutor] question about __init__ in a class
Mike.Hansen at atmel.com
Mon Nov 13 19:55:50 CET 2006
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of shawn bright
> Sent: Monday, November 13, 2006 11:45 AM
> To: tutor-python
> Subject: [Tutor] question about __init__ in a class
> 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
> self.monitor = monitor
> get some values from database
> value1 = somevalue
> value2 = someothervalue
> now i could call it like this:
> new_monitor = sensor.Sensor('', 'XJ191')
> 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.
> any suggestions ?
I don't know if it's cleaner, but it might be easier to read if you use
default named arguments.
def __init__(self, id = None, monitor = None):
new_monitor = sensor.Sensor(monitor = 'XJ191')
new_monitor = sensor.Sensor(id = '3433')
Check to make sure one or the other arguments is supplied. Otherwise
throw an exception.
Maybe there'll be some better ideas from other posters.
-------------- next part --------------
NOTICE: This e-mail transmission and any documents or files attached to
it contain information for the sole use of the above-identified individual or entity.
Its contents may be privileged, confidential, and exempt from disclosure under the law.
Any dissemination, distribution, or copying of this communication is strictly prohibited.
Please notify the sender immediately if you are not the intended recipient.
More information about the Tutor