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?

i know nammed dynamicly an varial in python with:

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

But i don't know how to make it on a variable class. When i try:

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

The exeception "NameError: global name 'ma_variable_dynamique' is not defined" is raised.

Example in 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

Community
  • 1
  • 1
Corentin Derbois
  • 325
  • 1
  • 3
  • 5

3 Answers3

2

User setattr:

class Controller(object):
    def __init__(self):
        var = 'ma_variable_dynamique'
        setattr(self, var, 'toto')
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
2

This only explains why what you're doing doesn't work (not how to do it).

Documentation from http://docs.python.org/library/functions.html#locals (emphasis mine):

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.

Jeremy Brown
  • 17,880
  • 4
  • 35
  • 28
0

Use setattr.

class Controller(object):
    def __init__(self):
        setattr(self, "ma_variable_dynamique", "toto")
J.J.
  • 5,019
  • 2
  • 28
  • 26