2011-08-08 57 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")