在类python之外调用方法

时间:2013-04-09 21:50:32

标签: python python-2.7

我对Python和OOP比较陌生,我正在尝试用类编写一个迷你冒险游戏,并且已经陷入了我的BattleEngine类。 这个想法是根据你的角色以及对手的力量和'智慧'来选择对抗或击败对手。 当我尝试在此处调用我的攻击方法时出现错误:

class Armory(Scene):

    def enter(self):
        print "This room appears to be some kind of armory. There are shelves full of weaponry lining"
        print "the walls. You walk around admiring the shiny weapons, you reach out to pick up a"
        print "massive battleaxe. Right as your fingers touch it you hear voices from behind the"
        print "next door. They sound like they're getting closer. As the voices grow nearer you must make"
        print "a decision. Will you stand and fight (enter 'fight') or will you use your wit to outsmart"
        print "your opponent(enter 'wit')?"
        decision = raw_input("> ")
        battle = BattleEngine()
        if decision == "fight":
            attack(self, Player.strength, 3)
            if player_wins:
                print "A man in light armour walks in and sees you with your sword drawn. A look of"
                print "shock and disbelief is on his face. You act quickly and lunge at him."
                print "The soldier struggles to unsheath his sword as you run him through."
                print "He collapses to the ground wearing the same look of disbelief."
                print "Your strength has increased by 1."
                Player.strength += 1
        elif decision == "wit":
            outwit(self, Player.wit, 3)    

这是我定义BattleEngine类的地方:

class BattleEngine(object):

    def attack(self, player_strength, nonplayer_strength):
        player_roll = randint(1,6)
        nonplayer_roll = randint(1,6)
        if (player_roll + player_strength) >= (nonplayer_roll + nonplayer_strength):
            return player_wins
        else: 
            return 'death'

    def outwit(self, player_wit, nonplayer_wit):
        player_roll = randint(1,6)
        nonplayer_roll = randint(1,6)
        if (player_roll + player_wit) >= (nonplayer_roll + nonplayer_wit):
            return player_wins
        else: 
            return 'death'     

一旦我在我的程序中达到这一点就会收到错误:'攻击全局名称未定义' 我不确定我到底做错了什么。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:4)

您需要在attack个实例上调用BattleEngine ,而 需要传入self:< / p>

battle = BattleEngine()
if decision == "fight":
    player_wins = battle.attack(Player.strength, 3)

请注意,您需要接收.attack()方法的返回值。

同样适用于.outwit()方法:

elif decision == "wit":
    player_wins = battle.outwit(Player.wit, 3)    

您可能需要在.attack().outwit()方法中修复返回值;而不是return player_winsreturn 'death',或许返回TrueFalse

Python会为您处理self参数,并会引用特定的BattleEngine实例。

这里并不是你真的需要类,例如,你的BattleEngine()类当前没有每个实例的状态。您不在任何方法中使用self,因为实例上没有任何内容可以将引用到