简体   繁体   中英

python: passing variable name to a class

I have a python class defined in a module1.py file:

class MBVar():
    def __init__(self, var_type, expression):
            self.var_type = var_type
            self.expression = expression
            ... ecc ...

I would like to be able to write in a main *.py file:

from module1 import MBVar
X = MBVar('integer', 6)

and add to my MBVar class:

self.name = ???

in such a way that: self.name = 'X'. Is it possible to do this??

Thanks

So I Assume you want to pass variable name and value as parameter and assign it to an object, to do that we don't need the type of the variable since python uses duck typing we just have to add the string representation of the variable name in the inbuilt dictionary __dict__ as key and the integer as value.

class MBVar():
    def __init__(self, var_name, expression):
        self.__dict__[var_name] = expression

    def add_later(self, var_name, expression):
        self.__dict__[var_name] = expression

    def get_name(self):
        return self.name


X = MBVar('name', 6)
print X.get_name() # prints 6
X.add_later('secint',4);
print X.secint #prints 4
X.__dict__['thirdint'] = 7
print X.thirdint #prints 7

I have a solution but i don't think that this is a very good coding practice. Moreover, it is a 2 steps process: it can't be done inside the __init__ method because till the end of this method, the object has not been yet associated to a variable.

class Foo:
    def __init__(self):
      self.__name = ""

    def set_name(self, name):
      self.__name = name

    def get_name(self):
      return self.__name

if __name__ == "__main__":
    a = Foo()
    b = Foo()
    c = Foo()

    dict_v = locals()

    v = "" 
    # this line initialize the variable of name "v" because of its entry in the locals() dict 
    #-> prevent "RuntimeError: dictionary changed size during iteration "

    for v in dict_v.keys():
      if isinstance(dict_v[v], Foo):
        # the process only happens for the objects of a specific class
        dict_v[v].set_name(v)

    #proof
    print(a.get_name())
    print(b.get_name())
    print(c.get_name())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM