繁体   English   中英

为什么我收到 TypeError: 'str' object is not callable when using eval() on string that is python code

[英]Why am I getting a TypeError: 'str' object is not callable when using eval() on string that is python code

我有以下代码以字符串的形式操作 function 并向 while 循环添加一个计时器,以查看它们是否需要 2 秒而不返回。 如果是这样,它会返回“错误,无限循环”。

现在,当我运行此代码时,它给了我一个“TypeError:'str' object 不可调用”。

def nico():
    otherTimer = '\n    current_time = time.time()\n    elapsed_time = current_time - start_time\n    print(elapsed_time)\n    if elapsed_time > 2:\n      return "error, infinite loop"'

    sample = '''def sample():\n  a = 1\n  while a == 1:\n    print("breh")
            '''


    for k in range(len(sample)): # insert srart time at top of function
        if sample[k] == ":":
            sample = sample[:k + 1] + "\n  start_time = time.time()\n" + sample[k+1:]
            break
    

    
    if "while" in sample: #insert timer in the while loop
        for i in range(len(sample)):
            if sample[i] + sample[i + 1] + sample[i + 2] + sample[i + 3] + sample[i + 4] == 'while':
                newstring = sample[i:]
    
                for j in range(len(newstring)):
                    if newstring[j] == ':':
                        print(sample[:i] + sample[i:] + otherTimer)
                        output = sample[:i] + sample[i:] + otherTimer
                        exec(output)

                        return eval('sample()')

我很困惑,因为这段代码做了我想要它做的事情,唯一的区别是我将字符串 function 存储为实际字符串而不是我的 exec() 语句中的变量:

def delly():
    exec('def sample():\n  start_time = time.time()\n\n  a = 1\n  while a == 1:\n    print("breh")\n            \n    current_time = time.time()\n    elapsed_time = current_time - start_time\n    print(elapsed_time)\n    if elapsed_time > 2:\n      return "error, infinite loop"')
    return eval('sample()')

sample变量正在遮蔽sample function。 Python 中没有不同的命名空间,因为所有内容都被视为 object。 因此,当调用exec来定义 function 时,它会立即被现有的sample字符串隐藏。 因此,调用eval将尝试将字符串变量作为 function 运行,返回看到的TypeError

例如:

# Defines a function named sample
def sample():
    print("Hello world!")

# Set a local variable with the same name and execute the global function
def test():
    sample = "some string"
    sample()

# Will throw a TypeError since the sample string shadows the function
test()

将示例 function 包装在一个字符串中以execeval将返回相同的结果:

def test():
    # Set a local variable named 'sample'
    sample = "some string"
    
    # Create a global function named 'sample'
    exec("def sample():\n    print('Hello world!')")

    # Throws TypeError as global function is shadowed by local variable
    eval('sample()')

test()

那么,解决方案呢? 您需要做的就是更改 function 或局部变量的名称。

为了进一步阅读这个问题,我会建议这个解释来理解,并在下面评论一个好的心态来处理这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM