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
這不是他想要的 – Claudiu