Python:使用YAML自动创建类方法
我一直在尝试使用Python:使用YAML自动创建类方法,python,python-3.x,class,methods,Python,Python 3.x,Class,Methods,我一直在尝试使用YAML配置文件创建一系列类似的方法。然而,我一直无法在网上找到什么,也无法找到答案 example.yml attributes: - a - b - c 示例类 import yaml class Test: def __init__(self): with open('example.yml', 'rb') as f: attrib_list = yaml.load(f) _list = []
YAML
配置文件创建一系列类似的方法。然而,我一直无法在网上找到什么,也无法找到答案
example.yml
attributes:
- a
- b
- c
示例类
import yaml
class Test:
def __init__(self):
with open('example.yml', 'rb') as f:
attrib_list = yaml.load(f)
_list = []
for name in attrib_list:
_list.append(self.__setattr__('_' + name, None))
# create similar methods in a loop
for name, _ in zip(attrib_list, _list):
@property
def name(self): # I know name is a string so cannot be this way but how if this can be done?
return _
@name.setter
def __set + _(self, v): # __set + '_' + name as method name
pass
@name.getter
def __get + _(self): # __get + '_' + name as method name
pass
有没有有效的方法通过循环配置文件来创建许多类似的方法
还是有更好的方法来处理这种性质的事情
谢谢。使用课堂
为什么你要创建一堆毫无意义的属性?@ Juanga.AcViLaGa,是针对我开发的一个定制的C++包装器,和C++交互的Python模块需要它。我只是对手头的问题做了一个MWE,跳过了与另一个对象的交互
class Test:
def __init__(self):
with open('102.yaml', 'rb') as f:
attrib_list = yaml.load(f)
_list = []
for name in attrib_list['attributes']:
_list.append(self.__setattr__('_' + name, None))
setattr(self.__class__, name,
property( Test.getprop(self,name), Test.setprop(self,name)))
@staticmethod
def getprop(self,name):
def xget(self):
print("Get {}".format(name))
return name
return xget
@staticmethod
def setprop(self,name):
def xset(self,value):
print("Set {} to {}".format(name,value))
return xset
>>> zz = Test()
>>> zz.a = "hallo"
Set a to hallo
>>> print(zz.a)
Get a
a