在if语句(Python)中调用方法时引发“str”object is not callable'

2024-05-29 03:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在if块中调用方法时,会得到一个TypeError,但是在if块之外调用该方法时,该方法将运行find:

randegense()从一个名为“酶”的字典中随机选择一个键:

def randenzyme(self):
    an_enzyme = choice(self.enzymes.keys())

它可以正确运行:

^{pr2}$

出现“str'is not callable”,但“object:

x = TCA()
user_input = raw_input('> ')
if user_input == "1":
    x.randenzyme()

在if块中调用方法时会发生什么情况?在

更新:这是完整的代码

from random import *
import sys
class TCA(object):
    def __init__(self):
        self.enzymes = {}
        self.enzymes['citrate synthase'] = ('oxaloacetate', 'citrate')
        self.enzymes['aconitase'] = ('citrate', 'isocitrate')
        self.enzymes['isocitrate dehydrogenase'] = ('isocitrate', 'alpha-ketoglutarate')
        self.enzymes['alpha-ketoglutarate dehydrogenase'] = ('alpha-ketoglutarate', 'succinyl-CoA')
        self.enzymes['succinyl-CoA synthetase'] = ('succinyl-CoA', 'succinate')
        self.enzymes['succinate dehydrogenase'] = ('succinate', 'fumarate')
        self.enzymes['fumarase'] = ('fumarate', 'malate')
        self.enzymes['malate dehydrogenase'] = ('malate', 'oxaloacetate')

    def randenzyme(self):
        an_enzyme = choice(self.enzymes.keys())
        print "Reaction (enzyme): %s" % an_enzyme
        return an_enzyme

x = TCA()
print 'Enter "1" for a random enzyme or "2" to exit'
choice = raw_input("> ")
if choice == '1':
    x.randenzyme()
elif choice == '2':
    sys.exit()

我得到的错误是:

Traceback (most recent call last):
File "/Users/sloria1/TCASO.py", line 24, in <module>
x.randenzyme()
File "/Users/sloria1/TCASO.py", line 16, in randenzyme
an_enzyme = choice(self.enzymes.keys())
TypeError: 'str' object is not callable

Tags: 方法selfaninputifobjectdefkeys

热门问题