I have a class who’s _init_ function requires quite a few keyword arguments. I’d like to be able to basically rewrite this bit of code so that it’s syntactically cleaner (less hard coding). Preferably I’d like to be able to get it so that simply adding a keyword argument to _init_ would change all the attributes/arguments in the null function respectively.
class Class :
def __init__ (self, kw0=0, kw1=1, kw2=2) :
''' The keyword arguments as strings. '''
self.Keys = ['kw0', 'kw1', 'kw2']
''' Their values. '''
self.Values = [kw0, kw1, kw2]
''' A dictionary made from the keys and values. '''
self.Dict = self.make_dict()
''' As individual attributes, '''
self.KW0, self.KW1, self.KW2 = self.Values
def make_dict (self) :
''' Makes a dictionary '''
keys = self.Keys
values = self.Values
_dict = {}
for i in xrange(len(keys)) :
key = keys[i]
value = values[i]
_dict[key] = value
return _dict
def null (self, kw0=None, kw1=None, kw2=None) :
''' The same keyword arguments as **__init__** but they all default
to **None**. '''
pass
c = Class()
print c.Keys
print c.Values
print c.Dict
print c.KW0
print c.KW1
print c.KW2
Why not accept any keyword arguments. You can use a class attribute for allowable keyword names and their default values.
If you want the same functionality in more than one method (e.g.
__init__()andnull()) then just break the argument handling code out into its own method and call it from both places.One downside is that
help()and other Python documentation tools won’t show the allowable keyword arguments, since they aren’t in your method signature.As an aside, I’m not quite sure why you’re storing keys and values separately. Just store them as a dictionary, then get the keys or values when you want them using the dictionary’s
.keys()or.values()method.