2013-04-06 36 views
0

嗨,我是在製作遊戲的過程中不斷變化的價值,我已經打了一個絆腳石這是我下面的代碼部分:Python的面向對象不是初始化函數

class player(object): 
    def __init__(self): 
     self.x = 10 
     self.y = 10 
     self.amount = 5 
     self.answer = 0 

    def move(self): 
     self.x += self.amount 
     self.y += self.amount 


while True: 
    player().move() 
    print player().x 

它可能是一個真正的基本的錯誤,但無論move()函數是否似乎都不會改變self.x或self.y的值,請有人戳我正確的方向!謝謝,我意識到我可能失去了一些東西非常基本的,我沒有與OO多少經驗

回答

4
player().move() # create a player and move it 
print player().x # create another player and print its x 

你的意思是:

aplayer = player() 
aplayer.move() 
print aplayer.x 

 

PS:常見的練習就是大寫類名:

class Player(object): 
    def __init__(self): 
     self.x = 10 
     self.y = 10 
     self.amount = 5 
     self.answer = 0 

    def move(self): 
     self.x += self.amount 
     self.y += self.amount 


player = Player() 
player.move() 
print player.x 

這樣就很容易區分類和對象。

+0

好吧,我明白了,我該如何糾正? – user2137452 2013-04-06 20:21:53

+0

優秀的歡呼聲:D – user2137452 2013-04-06 20:22:48

0

好的。什麼其他人說的是,你需要設置「玩家」爲如喬治變量,然後調用George.move()

所以

class Player(object): 
    def __init__(self): 
     self.x = 10 
     self.y = 10 
     self.amount = 5 
     self.answer = 0 

    def move(self): 
     self.x += self.amount 
     self.y += self.amount 

While True: 
    george = Player() 
    george.move() 
    print george.x 

,應該工作。你可以改變「喬治」到任何你想要的,只要確保它是一致的。