Steve D'Aprano <[email protected]> writes:
> class Spam:
> def __init__(self, bashful=10.0, doc=20.0, dopey=30.0,
> grumpy=40, happy=50, sleepy=60, sneezy=70):
> # the usual assign arguments to attributes dance...
> self.bashful = bashful
> self.doc = doc
> # etc.
def __init__(self, bashful=10.0, doc=20.0, dopey=30.0,
grumpy=40, happy=50, sleepy=60, sneezy=70):
# the usual assign arguments to attributes dance...
self.bashful = float(bashful)
self.doc = float(doc)
self.grumpy = int(grumpy)
# etc.
Now the constructor can take strings as keywords. You could even do
something like:
defaults = { 'bashful':10.0, 'grumpy':20, etc. }
def __init__(self, **kwargs):
# check for spurious kwargs
assert(not(set(kwargs)-set(defaults)))
for k in defaults:
v = type(defaults[k])(kwargs[k]) if k in kwargs else defaults[k]
setattr(self, k, v)
--
https://mail.python.org/mailman/listinfo/python-list