![](/img/trans.png)
[英]AttributeError: addinfourl instance has no __call__ method
[英]AttributeError : Class Instance has no __call__ method
我對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
我想這是因為你有一個變量名tree
(在tree.render()
),它與你的類名沖突。 稱之為Tree
會更好(而且更加pythonic ^^)。
您可能希望在for
循環中調用tree
變量而不是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()) <----------------------- 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()
編譯器可能認為您不是初始化類,而是調用其調用函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.