开发者

How to name my variable class dynamicly in python [duplicate]

This question already has answers here: Closed 11 years ago.

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->valid开发者_如何学Pythonate();
    }

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

Thx


User setattr:

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


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.


Use setattr.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜