2011-08-08 19 views
1

Possible Duplicates:
Python: Why can't I modify the current scope within a function using locals()?
How do you programmatically set an attribute in Python?如何命名在python

我的变量类动态地我知道nammed在Python动态地的维里有:

var = "my_var" 
locals()[var] = "coucou" 
print my_var 
>>coucou 

但我不知道如何使它在一个变量类。 当我尝试:

class Controller(object): 
    def __init__(self): 
     var = 'ma_variable_dynamique' 
     locals()[var] = 'toto' 
     print ma_variable_dynamique 

的exeception “NameError:全局名称 'ma_variable_dynamique' 没有定义” 上升。

例在PHP中:

class Users extends Controller{ 
    public $models = array(‘User’); 

    function login(){ 
     $this->User->validate(); 
    } 

    //Call in contructor 
    function loadModel(){ 
     foreach($this->models as $m){ 
      $_class = $m.’Model’;s 
      $this->{$m} = new $_class(); 
     } 
    } 
} 

THX

回答

2

用户setattr

class Controller(object): 
    def __init__(self): 
     var = 'ma_variable_dynamique' 
     setattr(self, var, 'toto') 
+0

这不是他想要的 – Claudiu

2

这不仅解释了为什么你在做什么不工作(不如何做到这一点) 。

文档从(强调矿):

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

0

使用setattr

class Controller(object): 
    def __init__(self): 
     setattr(self, "ma_variable_dynamique", "toto")