2014-07-10 72 views
1

有人可以糾正我對我一直有問題的錯誤!問題在於它不會在守門員和球員類中生成隨機整數。這個問題不允許我讓兩個「球員」移動。 錯誤:Python沒有約束的方法錯誤

import random 
def main(): 
    name = raw_input("Name: ") 
    kick = raw_input("\nWelcome " +name+ " to soccer shootout! Pick a corner to fire at! Type: TR, BR, TL, or BL! T = TOP B = BOTTOM L = LEFT R = RIGHT: ") 
    if Player.Shot == Goalie.Block: 
     print("\nThe goalie dives and blocks the shot!") 
    if Player.Shot != Goalie.Block: 
     print("\nThe ball spirals into the net!") 
     print(Player.Shot) 
     print(Goalie.Block) 
class Player(): 
    def __init__(self): 
     self.Shot() 
    def Shot(self): 
     shot = random.randint(0,3) 
     self.Shot = shot 
class Goalie(): 
    def __init__(self): 
     self.Block() 

    def Block(self): 
     block = random.randint(0,3) 
     self.Block = block 
main() 
+0

爲什麼不乾脆把射擊()和塊()的代碼放到INIT? – Ben

+0

您有一個屬性(例如'self.Block')和一個具有相同名稱*的方法(例如,erm,'self.Block')*。不要這樣做。正如@Ben所說,他們沒有做任何複雜的事情,你不能在'__init__'中做。 – jonrsharpe

+0

你可以請代碼/寫這個例子本? –

回答

2

你需要實例化類第一::

嘗試:

import random 
def main(): 
    name = raw_input("Name: ") 
    kick = raw_input("\nWelcome " +name+ " to soccer shootout! Pick a corner to fire at! Type: TR, BR, TL, or BL! T = TOP B = BOTTOM L = LEFT R = RIGHT: ") 
    player=Player() #error fixed:<-- called the class 
    goalie=Goalie() #error fixed:<-- called the class 
    if player.shot == goalie.block:#error fixed:<-- used that initiated class 
     print("\nThe goalie dives and blocks the shot!") 
    if player.shot != goalie.block: 
     print("\nThe ball spirals into the net!") 
     print(player.shot) 
     print(goalie.block) 

class Player: 
    def __init__(self): 
     self.Shot() 

    def Shot(self): 
     shot = random.randint(0,3) 
     self.shot = shot #error fixed:<-- attribute and method are same 


class Goalie: 
    def __init__(self): 
     self.Block() 

    def Block(self): 
     block = random.randint(0,3) 
     self.block = block #error fixed:<-- attribute and method are same 

main() 
+0

謝謝!有效! :) –