在python类之外调用方法

2024-05-12 19:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和OOP还比较陌生,我正在尝试编写一个带有类的小型冒险游戏,并且已经被我的战机类卡住了。 我们的想法是根据你的角色和对手的“实力”和“机智”来选择是否与对手作战。 当我试图在此处调用攻击方法时出错:

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)    

这里是我定义我的战机等级的地方:

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'     

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


Tags: andofthetoselfyouyourif
1条回答
网友
1楼 · 发布于 2024-05-12 19:45:00

您需要在您的BattleEngine实例上调用attack,而不需要传入self

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,因为实例上没有可以引用的内容。

相关问题 更多 >