AttributeError:类实例没有__call__方法

时间:2012-07-04 07:45:23

标签: python oop python-2.7 pygame attributeerror

我对python有点新,但熟悉OOP。我正在尝试使用PyGame编写游戏。基本上,我的目标是每隔几秒钟渲染一次树木并将树木移动到整个屏幕上。

所以这是我的代码:

from collections import deque
import pygame,random,sys

pygame.init()
size = 800,600
screen = pygame.display.set_mode(size)

class tree:
    def __init__(self):
            self.img = pygame.image.load("tree.png")
            self.rect = self.img.get_rect()
    def render(self):
            screen.blit(self.img,self.rect)
    def move(self,x,y):
            self.rect = self.rect.move(x,y)

#creating a queue of trees
trees = deque()

#appending the first tree on to the queue 
trees.append(tree())


while 1:


    for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()

    #appending tree() to trees queue every 300 ms
    if pygame.time.get_ticks() % 300 == 0:
            trees.append(tree())

    #rendering and moving all the tree rects of trees in the queue
    for tree in trees:
            tree.render()
            tree.move(20,2)
    pygame.display.flip()

但是当我执行此操作时,前几棵树成功生成,但PyGame窗口关闭,我收到此错误:

Traceback (most recent call last):
File "error.py", line 25, in <module>
trees.append(tree())
AttributeError: tree instance has no __call__ method

3 个答案:

答案 0 :(得分:22)

我想这是因为您的变量名称tree(在tree.render()中使用)与您的班级名称冲突。调用它Tree会更好(并且更加pythonic ^^)。

答案 1 :(得分:4)

您可能希望在tree循环中调用for变量而不是tree。它正在影响班级名称。

答案 2 :(得分:1)

您的上下文受到污染

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    #appending tree() to trees queue every 300 ms
    if pygame.time.get_ticks() % 300 == 0:
        trees.append(tree()) <----------------------- second time, this tree is not your class, but the last instance of tree

    #rendering and moving all the tree rects of trees in the queue
    for tree in trees: <-------------------- here, the last tree will get name with tree
        tree.render()
        tree.move(20,2) 
    pygame.display.flip()

编译器可能认为您不是在启动课程,而是调用其调用函数。