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). Pr开发者_StackOverflow中文版eferably 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
This is one thing I love about python. In your __init__
def __init__ (self, **kwargs):
self.__dict__.update(kwargs)
Will append those members defined in a dictionary kwargs
as members of the class.
EDITED - to reflect proper syntax for **kwargs, and update() instead of append()
Why not accept any keyword arguments. You can use a class attribute for allowable keyword names and their default values.
class Class(object):
_defaults = dict(kw0=42, kw1=None, kw2=True, kw3="Ni!")
def __init__(self, **kwargs):
# Raise exception if any non-supported keywords supplied
if set(kwargs.keys()) - set(self._defaults.keys()):
raise KeyError("unsupported keyword argument")
# Update our instance with defaults, then keyword args
self.__dict__.update(self._defaults)
self.__dict__.update(kwargs)
If you want the same functionality in more than one method (e.g. __init__()
and null()
) 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.
精彩评论