using __init__ with params ( somewhat long )

Mike Fletcher mfletch at tpresence.com
Tue Jan 16 15:32:51 EST 2001


class Convenient: # untested, of course
	# lower(attribute) to (realAttr, realValue)
	# you can do this at run-time instead, that's
	# left as an exercise for the reader...
	classAttributes = {
		'myattr1': ('myAttr1',None),
		'myattr2': ('myAttr2', 2),
		'myattr3': ('myPiAttr', 3.1416),
	}
	def __init__( self, **namedarguments ):
		# work with a copy of the attribute defns
		base = self.classAttributes.copy()
		# now update base from the passed args
		for key, value in namedarguments.items():
			# case-folding
			testkey = string.lower(key)
			# hack to be _sure_ we don't have
			# this key defaulting to None
			NULL = ()
			if base.get( testkey, NULL) is not NULL:
				base[testkey] = base[testkey][0], value
			else:
				# warn the user here! 
				raise AttributeError( 'Unknown attribute
name %s for Convenient object'%(key))
				pass
		# now actually update the instance, note that
		# we could have used self.__dict__.update if we'd
		# used the "realName" values as keys and the
		# realValue values as the whole value.  Oh well...
		for key, (realName, realValue) in base.items():
			setattr( self, realName, realValue )

I personally would skip the dictionary as a dictionary argument (you get
into "which dictionary should override if they have the same name"
questions, and people can use apply if they really need it).  If you want to
use it, just call namedarguments.update( yourdict ) (or
yourdict.update(namedarguments)) and you're off to the races.

HTH,
Mike

-----Original Message-----
From: corey at axcelerant.com [mailto:corey at axcelerant.com]
Sent: Tuesday, January 16, 2001 2:19 PM
To: python-list at python.org
Subject: using __init__ with params ( somewhat long )


Greetings all!


I'm new to Python ( from 5 odd years of Perl ), so please bare with 
me...  

...
1 - Allow a dictionary to be passed to __init__, containing as keys
    some or all of the attributes, along with their values of course.
...
2 - And/or allow named arguments to be passed into __init__, one
    for each attribute.
...




More information about the Python-list mailing list