开发者

Python: unpack dictionary inside a method

开发者 https://www.devze.com 2023-01-28 12:44 出处:网络
In Python, I want to create a new object by loading a number of variables into it. The easiest way is to pass a dictionary, but that makes programming very annoying: instead of self.health I have to c

In Python, I want to create a new object by loading a number of variables into it. The easiest way is to pass a dictionary, but that makes programming very annoying: instead of self.health I have to call self.params['health'] all the time. Is there any way to set variable names (fields) dynamically?

I have:

DEFAULT_PARAMS = {
    'health': 10,
    'position': []
}

def __init__(self, params = DEFAULT_PARAMS):
    self.params = params
    print self.params['health']

I want to have:

DEFAULT_PARAMS = {
    'health': 10,
    'position': []
}

class Name()开发者_开发知识库:
    def load(self, params):
        # what goes here?

    def __init__(self, params = DEFAULT_PARAMS):
        self.load(params)
        print self.health


class Name(object):
    def __init__(self, *params):
        self.__dict__.update(DEFAULT_PARAMS)
        self.__dict__.update(params)

b = Name(position=[1,2])
print b.position


You can use

setattr(self, name, value)

to create a new attritbute of self with the dynamic name name and the value value. In your example, you could write

def load(self, params):
    for name, value in params.iteritems():
        setattr(self, name, value)


If you use the **kwargs syntax then this makes your construction even more flexible when creating the object:

class MyHealthClass(object):
    def __init__(self, *args, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])
        if not hasattr(self, 'health'):
            raise TypeError('Needs a health')
        print self.health

You can then call this with your dictionary like this:

>>> myvar = MyHealthClass(**DEFAULT_PARAMS)
10

Or using keyword args:

>>> myvar = MyHealthClass(healh=10, wealth="Better all the time")
10
>>> print myvar.health
10
>>> print myvar.wealth
Better all the time


You can make attributes for the instance from items coming in the dictionary:

def __init__(self, params=DEFAULT_PARAMS):
  ...
  for k,v in DEFAULT_PARAMS.iteritems():
    setattr(self, escape_attr_name(k), v)
  ...

In escapse_attr_name you take care of characters which aren't allowed in attribute names, but are present in the keys.

0

精彩评论

暂无评论...
验证码 换一张
取 消