Python ';str';对象不可调用,用作参数

Python ';str';对象不可调用,用作参数,python,python-2.7,Python,Python 2.7,我想写一个程序作为练习,用两个数学函数中的一个计算从a到b的积分值。我的函数积分应该有f作为积分的数学函数 from math import * def g(x): return float(x) * float(x) + 3 def h(x): return math.cos(float(x) * float(x)) def integrate(f, a, b, n): H = (abs(float(a) - float(b)))/float(n)

我想写一个程序作为练习,用两个数学函数中的一个计算从a到b的积分值。我的函数积分应该有f作为积分的数学函数

from math import *

def g(x):
        return float(x) * float(x) + 3

def h(x):
    return math.cos(float(x) * float(x))

def integrate(f, a, b, n):
    H = (abs(float(a) - float(b)))/float(n)
    ans = 0
    xWaarde = a - H/2
    print xWaarde
    for k in range(1, n+1):
        xWaarde = xWaarde + H
        ans = ans + f(xWaarde) * H
    return ans

print 'available functions:'
print 'g(x) = x^2+3'
while True:
    print 'h(x) = cos(x^2)'
    aIn = float(raw_input('integral from a = '))
    bIn = float(raw_input('to b = '))
    nIn = int(raw_input('Number of subintervals: '))
    while True:
        funcIn = raw_input('Which function do you want to use? (g or h): ')
        if funcIn == 'g':
            integrate(g,aIn,bIn,nIn)
            break
        elif funcIn == 'h':
            integrate(h,aIn,bIn,nIn)
            break
        else:
            print 'This function is not available'


    print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)
    doorg = raw_input('Do you want to continue? (y or n): ')
    if doorg == 'n':
        break
    else:
        print
完整回溯如下所示:

Traceback (most recent call last):
  File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 38, in <module>
    print 'The definite integral is', integrate(funcIn, aIn, bIn, nIn)
  File "C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py", line 16, in integrate
    ans = ans + f(xWaarde) * H
TypeError: 'str' object is not callable
回溯(最近一次呼叫最后一次):
文件“C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py”,第38行,在
打印“定积分是”,积分(funcIn,aIn,bIn,nIn)
文件“C:/Users/Nick van Stijn/Desktop/Python/Assignment 3.1.py”,第16行,在integrate中
ans=ans+f(xWaarde)*H
TypeError:“str”对象不可调用
编辑:已解决
我犯了一个错误,在我根本不需要调用的时候调用了一个函数。

问题是,您使用适当的函数调用了
integrate
f
g
,但随后放弃结果,而是再次调用
integrate
打印,这次只传递函数的名称,
funcIn

相反,您应该将结果存储在变量中,例如:

result = None
while result is None:
    funcIn = raw_input('Which function do you want to use? (g or h): ')
    if funcIn == 'g':
        result = integrate(g,aIn,bIn,nIn)
    elif funcIn == 'h':
        result = integrate(h,aIn,bIn,nIn)
    else:
        print 'This function is not available'

print 'The definite integral is', result
此外,您可以使用
dict
将函数名映射到实际函数,而不是使用大量的
if/elif/else

functions = {'h': h, 'g': g}
while result is None:
    funcIn = raw_input('Which function do you want to use? (g or h): ')
    if funcIn in functions:
        result = integrate(functions[funcIn],aIn,bIn,nIn)
    else:
        print 'This function is not available'

问题是,您使用适当的函数调用
integrate
f
g
,但随后放弃结果,而是再次调用
integrate
进行打印,这次只传递函数名
funcIn

相反,您应该将结果存储在变量中,例如:

result = None
while result is None:
    funcIn = raw_input('Which function do you want to use? (g or h): ')
    if funcIn == 'g':
        result = integrate(g,aIn,bIn,nIn)
    elif funcIn == 'h':
        result = integrate(h,aIn,bIn,nIn)
    else:
        print 'This function is not available'

print 'The definite integral is', result
此外,您可以使用
dict
将函数名映射到实际函数,而不是使用大量的
if/elif/else

functions = {'h': h, 'g': g}
while result is None:
    funcIn = raw_input('Which function do you want to use? (g or h): ')
    if funcIn in functions:
        result = integrate(functions[funcIn],aIn,bIn,nIn)
    else:
        print 'This function is not available'

您使用的是字符串形式的函数文本名称,而不是对函数对象本身的引用。虽然有一些黑客技术可以从字符串名派生函数对象,但它们很难维护,而且容易出错。因为在python中,函数与任何其他对象(所谓的“第一类”对象)一样都是对象,所以它们并没有真正命名,只有对函数的引用才有名称

这是一个很好的例子,字典很方便,特别是如果您希望以后添加更多函数。我们可以将文本键(用户输入的内容)映射到任何python对象,包括一个函数:

from math import *

def g(x):
        return float(x) * float(x) + 3

def h(x):
    return math.cos(float(x) * float(x))

# Store references to the functions in a dictionary
# with the keys as the text name (the names need not match)
funcs = {'g': g, 'h': h}        #  <<<<  ADDED

def integrate(f, a, b, n):
    H = (abs(float(a) - float(b)))/float(n)
    ans = 0
    xWaarde = a - H/2
    print xWaarde
    for k in range(1, n+1):
        xWaarde = xWaarde + H
        ans = ans + f(xWaarde) * H
    return ans

print 'available functions:'
print 'g(x) = x^2+3'
while True:
    print 'h(x) = cos(x^2)'
    aIn = float(raw_input('integral from a = '))
    bIn = float(raw_input('to b = '))
    nIn = int(raw_input('Number of subintervals: '))
    while True:
        funcIn = raw_input('Which function do you want to use? (g or h): ')

        # THIS CODE CHANGED - note the simplification
        # we just test for membership of the dictionary
        if funcIn in funcs:
            integrate(funcs[funcIn],aIn,bIn,nIn)
            break
        else:
            print 'This function is not available'

    # THIS CODE CHANGED (note first argument to integrate)
    print 'The definite integral is', integrate(funcs[funcIn], aIn, bIn, nIn)
    doorg = raw_input('Do you want to continue? (y or n): ')
    if doorg == 'n':
        break
    else:
        print
从数学导入*
def g(x):
返回浮点数(x)*浮点数(x)+3
def h(x):
返回数学cos(浮点(x)*浮点(x))
#在字典中存储对函数的引用
#以键作为文本名称(名称不必匹配)

funcs={'g':g,'h':h}}您使用的是字符串形式的函数文本名称,而不是对函数对象本身的引用。虽然有一些黑客技术可以从字符串名派生函数对象,但它们很难维护,而且容易出错。因为在python中,函数与任何其他对象(所谓的“第一类”对象)一样都是对象,所以它们并没有真正命名,只有对函数的引用才有名称

这是一个很好的例子,字典很方便,特别是如果您希望以后添加更多函数。我们可以将文本键(用户输入的内容)映射到任何python对象,包括一个函数:

from math import *

def g(x):
        return float(x) * float(x) + 3

def h(x):
    return math.cos(float(x) * float(x))

# Store references to the functions in a dictionary
# with the keys as the text name (the names need not match)
funcs = {'g': g, 'h': h}        #  <<<<  ADDED

def integrate(f, a, b, n):
    H = (abs(float(a) - float(b)))/float(n)
    ans = 0
    xWaarde = a - H/2
    print xWaarde
    for k in range(1, n+1):
        xWaarde = xWaarde + H
        ans = ans + f(xWaarde) * H
    return ans

print 'available functions:'
print 'g(x) = x^2+3'
while True:
    print 'h(x) = cos(x^2)'
    aIn = float(raw_input('integral from a = '))
    bIn = float(raw_input('to b = '))
    nIn = int(raw_input('Number of subintervals: '))
    while True:
        funcIn = raw_input('Which function do you want to use? (g or h): ')

        # THIS CODE CHANGED - note the simplification
        # we just test for membership of the dictionary
        if funcIn in funcs:
            integrate(funcs[funcIn],aIn,bIn,nIn)
            break
        else:
            print 'This function is not available'

    # THIS CODE CHANGED (note first argument to integrate)
    print 'The definite integral is', integrate(funcs[funcIn], aIn, bIn, nIn)
    doorg = raw_input('Do you want to continue? (y or n): ')
    if doorg == 'n':
        break
    else:
        print
从数学导入*
def g(x):
返回浮点数(x)*浮点数(x)+3
def h(x):
返回数学cos(浮点(x)*浮点(x))
#在字典中存储对函数的引用
#以键作为文本名称(名称不必匹配)

funcs={g':g,'h':h}#例如,
f=='g'
在这一点上-那只是一个字符串,你希望调用它做什么?只是要清楚,错误在
print'the defin定积分是',integrate(funcIn,aIn,bIn,nIn)
,而不是原始的积分
funcIn
是字符串,而不是
g
h
本身。例如
f=='g'
在这一点上-那只是一个单字符字符串,你希望调用它做什么?只是要清楚,错误在
打印“定积分是”,积分(funcIn,aIn,bIn,nIn)
,而不是原始积分
funcIn
是字符串,而不是
g
h
本身。这是真正解释错误发生原因的唯一答案。是的,谢谢,这是一个愚蠢的错误,我使用的代码是从我以前做过的一个练习中复制的,带有“打印”定积分的行是“应该删除。这是唯一能够解释错误发生原因的答案。是的,谢谢,这是一个愚蠢的错误,我使用的代码是从我以前做的练习中复制的,带有“print'the definite integral is'”的行应该删除。虽然这解决了OP的问题并引入了更好的技术,请注意,
行打印“定积分是”,integrate(funcs[funcIn],aIn,bIn,nIn)
是打破原始代码的东西,这会很好。@mad物理学家:公正的评论。我没有把它包括在内,因为错误的原因已经解释清楚了。我的目的只是想展示一种更好的技术。虽然这解决了OP的问题并引入了一种更好的技术,但要注意的是,
print'the definal integral is',integrate(funcs[funcIn],aIn,bIn,nIn)
这一行是打破原始代码的好方法。@MadPhysicator:公正的评论。我没有把它包括在内,因为错误的原因已经解释清楚了。我的目的只是展示一种更好的技术。