从string创建函数时exec不工作

问题描述 投票:0回答:2

长话短说,我正在测试python中的方法的一些动态属性注入。

现在我遇到的问题是,当我在我的getter和setter字符串上调用exec()将它们转换为动态创建的函数时,它们会保留字符串。

def _injectProperties(self): 
        """docstring"""

        for p in self.InputParameters:
            index = p.Order
            name = p.Name.lstrip('@')
            pName = p.Name

            fnGet = (
                "def get(self): \n"
                "    rtnVal = [p.Value for p in self.InputParameters "
                "        if p.Name == '{0}'][0] \n"
                "    return rtnVal ").format(p.Name)

            fnSet = (
                "def set(self, value): \n"
                "    prop = [p for p in self.InputParameters "
                "        if p.Name == '{0}'][0] \n"
                "    prop.Value = value \n"
                "    return ").format(p.Name)

            exec(fnGet) in locals()
            exec(fnSet) in locals()

            self._addprop(name, fnGet, fnSet)

        return

因此,基本上在上面的代码中,_addprop是一个函数,它只是简单地创建了一个类的副本,并为它设置了一个属性:

setattr(cls, name, property(fget=getter, fset=setter, fdel=destructor, doc=docstring))

为什么在这个上下文中,在调用fnGetfnSet之后,exec(fnGet)exec(fnSet)变量仍然引用了get和set函数的字符串表示?

python python-3.x properties setter getter
2个回答
1
投票

你没有在你的问题中提供MCVE。所以我编造了一些可以运行的东西来说明你如何做到这一点(尽管我认为@Ned Batchelder可能有更好的建议)。

请注意,这也表明了我认为嵌入函数源代码的方法更好。

from textwrap import dedent

class InputParameter:  # Mock for testing
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)


class Class:
    def __init__(self):
        self.InputParameters = [  # For testing
            InputParameter(Order=42, Name='@foobar'),
        ]

    def _addprop(self, name, getter, setter):
        print('_addprop({!r}, {}, {})'.format(name, getter, setter))

    def _injectProperties(self):
            """docstring"""

            for p in self.InputParameters:
                index = p.Order
                name = p.Name.lstrip('@')
                pName = p.Name

                fnGet = dedent("""
                    def get(self):
                        rtnVal = [p.Value for p in self.InputParameters
                                    if p.Name == '{0}'][0]
                        return rtnVal
                """).format(p.Name)

                fnSet = dedent("""
                    def set(self, value):
                        prop = [p for p in self.InputParameters
                                    if p.Name == '{0}'][0]
                        prop.Value = value
                        return
                """).format(p.Name)

                locals_dict = {}
                exec(fnGet, globals(), locals_dict)
                exec(fnSet, globals(), locals_dict)

                self._addprop(name, locals_dict['get'], locals_dict['set'])

            return

cls = Class()
cls._injectProperties()

输出:

_addprop('foobar', <function get at 0x00270858>, <function set at 0x00572C00>)

1
投票

您可以使用__getattr__而不是使用exec来注入属性。在缺少属性时调用它。

我认为这可以满足您的需求:

def __getattr__(self, attr):
    for p in self.InputParameters:
        if p.Name == attr:
            return p.Value

def __setattr__(self, attr, value):
    for p in self.InputParameters:
        if p.Name == attr:
            p.Value = value
            break
© www.soinside.com 2019 - 2024. All rights reserved.