“ float”对象在一种情况下不可调用,但在另一种情况下可使用

时间:2018-08-06 07:25:23

标签: python python-3.x

这是代码,调用时应取以太x或y坐标的平均值,而调用y时却给出错误。

import turtle
turtle.setup()
A = turtle.Turtle()

####################################################
total_of_x_scores = 0
total_of_y_scores = 0
number_of_x_scores = 0
number_of_y_scores = 0
average = 0

def average(axis):
    global total_of_x_scores
    global total_of_y_scores
    global number_of_x_scores
    global number_of_y_scores
    global average
    if axis=='x'or'X':
        x=A.xcor()
        total_of_x_scores += x #adding curent score
        number_of_x_scores += 1
        average=total_of_x_scores/number_of_x_scores
    else:
        y=A.ycor()
        total_of_y_scores += y #adding curent score
        number_of_y_scores += 1
        average=total_of_y_scores/number_of_y_scores
    return average
######################################################

while True:
    A.goto(100,100)
    print('x',average('x'))
    print('y',average('y'))

这是错误,请注意在x上没有错误

x 100.0
Traceback (most recent call last):
 File "C:/Users/Jack/Desktop/average def.py", line 34, in <module>
    print('y',average('y'))
TypeError: 'float' object is not callable

1 个答案:

答案 0 :(得分:0)

即使您开始将average定义为一个数字,但随后仍将average定义为一个函数。因此,第一次调用average()时,它正确地理解为一个函数。但是由于average是全局的,所以当函数完成时,average又回到了数字。

这是该问题的演示:

foo = 0

def foo():
    global foo
    foo = 1.0
    return foo

print('now foo is:', foo, 'and foo class is:', type(foo))
print('call foo() to get foo =', foo())
print('now foo is:', foo, 'and foo class is:', type(foo))
print('call foo() to get foo =', foo())

输出:

now foo is: <function foo at 0x1a27e108c8> and foo class is: <class 'function'>
call foo() to get foo = 1.0
now foo is: 1.0 and foo class is: <class 'float'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1138-008d99aeffef> in <module>()
      2 print('call foo() to get foo =', foo())
      3 print('now foo is:', foo, 'and foo class is:', type(foo))
----> 4 print('call foo() to get foo =', foo())

TypeError: 'float' object is not callable