gpt4 book ai didi

Python:使用 YAML 自动创建类方法

转载 作者:行者123 更新时间:2023-12-01 09:00:30 25 4
gpt4 key购买 nike

我一直在尝试使用 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

有没有有效的方法可以通过循环配置文件来创建许多类似的方法?

或者有更好的方法来处理这种性质的事情吗?

谢谢。

最佳答案

使用property

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

关于Python:使用 YAML 自动创建类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52490621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com