代码之家  ›  专栏  ›  技术社区  ›  dustin

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

  •  1
  • dustin  · 技术社区  · 7 年前

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

    有没有一种有效的方法通过在配置文件中循环来创建许多类似的方法?

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   napuzba    7 年前

    使用 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