[Tutor] question about __init__ in a class
Kent Johnson
kent37 at tds.net
Mon Nov 13 20:14:22 CET 2006
Mike Hansen wrote:
>
>
>> -----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.
> 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):
>
> Calling it
> 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.
That is a good solution. Another way is to make new functions that wrap
the constructor. In sensor.py add:
def fromId(id):
return Sensor(id, None)
def fromMonitor(monitor):
return Sensor(None, monitor)
Then client code is
new_monitor = sensor.fromMonitor('XJ191')
new_monitor = sensor.fromId('3433')
Kent
More information about the Tutor
mailing list