[英]python: passing variable name to a class
I have a python class defined in a module1.py file: 我在module1.py文件中定义了一个python类:
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: 我希望能够在主* .py文件中编写:
from module1 import MBVar
X = MBVar('integer', 6)
and add to my MBVar class: 并添加到我的MBVar类中:
self.name = ???
in such a way that: self.name = 'X'. 以这样的方式: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. 因此,我假设您想将变量名和值作为参数传递并将其分配给一个对象,因为Python使用鸭子类型,所以我们不需要变量的类型,我们只需要添加变量名的字符串表示形式在内置字典
__dict__
作为键,在整数中作为值。
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. 此外,它是一个两步过程:不能在
__init__
方法内部完成,因为直到该方法结束之前,该对象尚未与变量关联。
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.