我正在尝试创建动态自变量。
我有以下代码
import json
class ABC:
def __init__(self):
with open("file") as f:
data = json.load(f)
fields = data["messages"] # it returns a string as "val1|val2|val3|val4"
new_fields = fields.split("|")
##I want to create self variables as self.val1 = <some value>, self.val2 = <some_value>, self.val3 = <some_value>, self.val4 = <some_value>
a = "version"
self.a = 10 ### I want to retreive self.version since a is version
print ("***************", self.version)
def pri(self):
print("*************", self.version)
我没有得到输出。我希望输出为10。我想动态创建很多变量。
我想创建动态自变量。我将从另一个文件中读取变量并创建一个类变量。在python中有可能吗?
那些给予负面评论的人,请帮助我写得更好。请添加评论,为什么您觉得自己不赞成
答案 0 :(得分:1)
您可以使用setattr
进行以下操作,
class ABC:
def __init__(self, args, val):
a = args
self.a = val ### I want to retreive self.version since a is version
setattr(self, a, self.a)
print ("***************", self.version)
def pri(self):
print("*************", self.version)
a = ABC("version", 10)
a.pri()
('***************', 10)
('*************', 10)
答案 1 :(得分:0)
#!/usr/bin/env python
class ABC:
def __init__(self):
self.version = 10 ### I want to retreive self.version since a is version
def pri(self):
print("*************", self.version)
if __name__ == '__main__':
o = ABC()
o.pri()
输出:
************* 10
您可能想要:
#!/usr/bin/env python
class ABC:
def __init__(self, version):
self.version = version ### I want to retreive self.version since a is version
def pri(self):
print("*************", self.version)
if __name__ == '__main__':
o = ABC(10)
o.pri()
输出与先前示例相同
答案 2 :(得分:0)
如果我正确理解了您的问题,则可以使用字典。例如:
class Myclass:
def __init__(self):
self.__fields = {}
self.__fields["version"] = 10
### I want to retreive self.version since a is version
a = "version"
self.__fields[a] = 10
print ("***************", self.__fields["version"])
def pri(self):
print ("***************", self.__fields["version"])
obj = Myclass()
obj.pri()
我省略了json代码,因为我没有要复制和测试的原始文件。
编辑:
要使用其他名称,您可以使用property
(此处显示getter):
class Myclass:
...
def pri(self):
print ("***************", self.val1)
@property
def val1(self):
return self.__fields["version"]
obj = Myclass()
print(obj.val1)
答案 3 :(得分:-2)
您创建了一个类,但未实例化它,也没有调用main的要求 将此添加到您的代码中
if __name__=="__main__":
abc=ABC()
abc.init()
abc.pri()