在Python中,我想通过加载一些变量来创建一个新对象.最简单的方法是传递字典,但这使编程非常烦人:而不是self.health我必须一直调用self.params ['health'].有没有办法动态设置变量名称(字段)?
我有:
DEFAULT_PARAMS = {
'health': 10,
'position': []
}
def __init__(self, params = DEFAULT_PARAMS):
self.params = params
print self.params['health']
Run Code Online (Sandbox Code Playgroud)
我希望有:
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
Run Code Online (Sandbox Code Playgroud)
class Name(object):
def __init__(self, *params):
self.__dict__.update(DEFAULT_PARAMS)
self.__dict__.update(params)
b = Name(position=[1,2])
print b.position
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2929 次 |
最近记录: |