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

标签 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 = []
        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/

相关文章:

python - 如何在 Clojure 中实现递归 DFS(不使用向量/堆栈)

python-3.x - 收集特殊键和值并将其放在字典中

java - 当父类是引用类型并通过方法传递时,如何从子类访问属性?

python - 如何从列表中删除 '\xe2'

Python 列表初学者

python - Matplotlib 日期代码 - 没有明显原因超出 Locator.MAXTICKS 错误

python - 从类中创建对象时如何预留内存?

php - 在 PHP 中使用命名空间

javascript - 使用类而不是使用抛出对象作为返回值的函数有什么优点?

python - bash 中的 python 参数中的变量为空?