【问题标题】:self only in scope for eval when self is referred to beforehand in same scope/function当 self 在同一范围/功能中预先被引用时,self 仅在 eval 范围内
【发布时间】:2019-07-29 15:02:22
【问题描述】:

在下面的代码中eval调用成功:

from zeep import Client
from zeep import xsd
from zeep.plugins import HistoryPlugin

class TrainAPI:
    def __init__(self,LDB_TOKEN):
        if LDB_TOKEN == '':
            raise Exception("Please configure your OpenLDBWS token")
        WSDL = 'http://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2017-10-01'
        history = HistoryPlugin()
        self.client = Client(wsdl=WSDL, plugins=[history])

        header = xsd.Element(
            '{http://thalesgroup.com/RTTI/2013-11-28/Token/types}AccessToken',
            xsd.ComplexType([
                xsd.Element(
                    '{http://thalesgroup.com/RTTI/2013-11-28/Token/types}TokenValue',
                    xsd.String()),
            ])
        )
        self.header_value = header(TokenValue=LDB_TOKEN)
        self.token = LDB_TOKEN
        return

    def __getattr__(self, action):
        def method(*args,**kwargs):
            print(action,args,kwargs)
            print(self)
            return eval(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])")
        return method

但是,如果删除print(self) 行,则会引发以下错误:

File "C:/Users/-/Documents/-/main.py", line 32, in method
    return eval(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])")
  File "<string>", line 1, in <module>
NameError: name 'self' is not defined

对不起,如果我遗漏了一些明显的东西,但我的问题是:为什么没有定义 self,除非我事先在 method 函数中调用了引用它的东西(例如 print(self))? 看起来很复杂,因为回溯最终引用了 &lt;string&gt; 的第 1 行...

编辑:尝试这样做也会返回错误:

def __getattr__(self, action):
        def method(*args,**kwargs):
            print(action,args,kwargs)
            print(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])")
            return eval(f"self.client.service.{action}(*args,**kwargs, _soapheaders=[self.header_value])")
        return method

也许我不明白范围或格式字符串是如何工作的。

【问题讨论】:

标签: python python-3.x scope eval format-string


【解决方案1】:

原因有点深入到 python 的工作原理,如果你真的想要,我可以告诉你,但为了解决你的实际问题,答案是尽可能避免使用 eval,因为通常有更好的方法。在这种情况下:

method = getattr(self.client.service, action)
return method(*args,**kwargs, _soapheaders=[self.header_value])

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    相关资源
    最近更新 更多