【问题标题】:In python, steal a class B method AND use it as an instance of class A from within a class A method在 python 中,窃取一个 B 类方法并将其用作 A 类方法中的 A 类实例
【发布时间】:2019-06-26 15:22:57
【问题描述】:

我已经成功地从一个类 (darkMage) 中“spellsiphon”(窃取)一个方法,以提供给玩家类 (Player)。

然而,“stolen”方法似乎仍然属于 darkMage 类——换句话说,当玩家施放偷来的法术时,它仍然(在所有方面)读取为 darkMage 施放法术。

你能帮忙吗?我已经这样做了:

  • 将偷来的 darkMage() 法术添加到玩家的法术书(列表)中
  • 成功地将“施法”命令与法术书中的物品配对

我想: - 让 Player() 施法而不是暗法师(当被盗的方法被调用时,它作为暗法师而不是玩家运行)

class Player(livingThing):
    def __init__(self,name="The Stranger", HP=10, MP=5, strength=1, intellect=1, spirit=1, luck=5, gil=6):
        self.name = name
        self.HP = HP
        self.MP = MP
        self.gil = gil
        self.strength = strength
        self.intellect = intellect
        self.spirit = spirit
        self.luck = luck
        self.spellbook = []

    def act(self, enemy):
        actions = {
        "a" : self.attack, 
        "heal" : self.heal, 
        "flee" : self.flee,
        "cast" : self.cast,
        "siphon" : self.spellsiphon
        }
        #Takes input from the player
        self.safe = False
        while ((self.HP > 0) and (enemy.HP > 0)) and (self.safe != True):
            decision = input("What would you like to do? ")

            #Sets the user's input as lower-case and checks for it within the dictionary
            if decision.lower() in actions:
                actions[decision.lower()](enemy)
                if self.safe != True:
                    enemy.agreact(self)
                    self.printHP(enemy)

            else:
                print("That didn't workkkkkk!  Try again.")

    # Prints both player and enemy HP
    def printHP(self, enemy):
        print("{0}'s' HP: {1} \n{2}'s HP: {3}".format(self.name, self.HP, enemy.name, enemy.HP))

    # Allows the player to attack an enemy (currently functional)
    def attack(self, enemy):
        enemy.HP -= self.strength
        print("You strike {0} for {1} damage!".format(enemy.name, self.strength))
        #player.printHP(enemy)

    # Allows the player to heal a certain amount of health based on its "spirit" stat (currently functional)
    def heal(self, enemy):
        healed = randint(0, self.spirit)
        self.HP += healed
        print("You've healed for {0}!".format(healed))
        #player.printHP(enemy)

    #Allows the player to attempt to run away
    def flee(self, enemy):
        randluck = randint(0, self.luck)
        if randluck > 3:
            print("You successfully escaped!")
            self.safe = True
        else:
            print("You weren't able to escape!")

    def cast(self, enemy):
        if len(self.spellbook) != 0:
            spellchoice = randint(0, len(self.spellbook)-1)
            self.spellbook[spellchoice](self)
        else:
            print("You don't have any spells to cast!")

### SPELLSIPHON IS CURRENTLY BROKEN; IT -DOES- SIPHON THE SPELL BUT ONLY ALLOWS THE DARK MAGE TO CONTINUE CASTING ###
    def spellsiphon(self, enemy):
        if len(enemy.spellbook) != 0:
            randspell = randint(0, len(enemy.spellbook)-1)
            stolenspell = darkMage().spellbook[randspell]
            #(type(enemy).__name__).__init__(self, stolenspell)
            self.spellbook.append(stolenspell)
            print("You've successfully stolen {0} from {1}!".format("stolenspell", enemy.name))
        else:
            print("You can't steal a spell from {0}!".format(enemy.name))


# Anything that can act with/against the player
class Actor(livingThing):
    def __init__(self, name="Unknown Entity", HP=10, MP=2, strength=1, intellect=1, spirit=3, gil=3):
        self. name = name
        self.HP = HP
        self.MP = MP
        self.gil = gil
        self.strength = strength
        self.intellect = intellect
        self.spirit = spirit
        self.abilities = [self.strike, self.heal]
        def printabilities():
            print(self.abilities)

    # Chooses how your opponent will respond to your attack
    def agreact(self, player):
        choice = randint(0, len(self.abilities)-1)
        self.abilities[choice](player)

    # A basic "hit back" reaction from your opponent--everyone can do this
    def strike(self, player):
        player.HP -= self.strength
        print("{0} hit {1} for {2}!".format(self.name, player.name, self.strength))

    def heal(self, enemy):
        healed = randint(0, self.spirit)
        self.HP += healed
        print("{0} healed for {1}!".format(self.name, healed))


### CURRENT VERSION SUPPORTS THE ADDITION OF NEW ABILITIES IN CHILD CLASSES VIA THE "super().__init__()" method! ###
class Enemy(Actor):
    def __init__(self):
        super().__init__()
        self.abilities.append(self.cast)
        self.name = "Unknown Enemy"
        self.HP = 600
        self.spellbook = []
    def cast(self, opponent):
            if len(self.spellbook) != 0:
                spellchoice = randint(0, len(self.spellbook)-1)
                self.spellbook[spellchoice](opponent)

class darkMage(Enemy):
    def __init__(self):
        super().__init__()
        self.player = Player()
        self.name = "Dark Mage"
        self.spellbook.extend((self.fireball, self.icenova))
    def fireball(cls, opponent):
        choice = randint(cls.intellect*1, cls.intellect*2)
        spellname = "Fireball"
        opponent.HP -= choice
        print("{0} casted fireball for {1} damage!".format(cls.name, choice))
    def icenova(cls, opponent):
        opponent.HP -= cls.intellect
        choice = randint(0,1)
        name = "Ice Nova"
        if choice == 1:
            frozen = True
        else:
            frozen = False
        print("{0} casted ice nova for {1} damage!".format(cls.name, cls.intellect))
        if frozen == True:
            print("{0} has been frozen solid!".format(opponent.name))

【问题讨论】:

    标签: python class object methods instance


    【解决方案1】:

    看起来您希望将法术与敌人/玩家分离。您可以通过使它们成为静态方法而不是实例方法来做到这一点(您使用的是def fireball(cls,..) 但没有使用@classmethod 装饰器,因此它们实际上是实例方法)。静态方法不会像类/实例方法一样自动传递它们附加到的类/实例,因此您可以传递它们可以被“窃取”和“强制转换”(调用)而无需记住原始所有者。

    这是一个简单的例子:

    class DarkMage:
        def __init__(self, name):
            self.name = name
            self.spellbook = [self.fireball]
    
        @staticmethod
        def fireball(caster, target):
            print("{} casted fireball on {} for 10 damage".format(caster.name, target.name))
    
    
    class Player:
        def __init__(self, name):
            self.name = name
            self.spellbook = []
    
        def spellsiphon(self, enemy):
            if enemy.spellbook:
                spellchoice = randint(0, len(enemy.spellbook)-1)
                self.spellbook.append(enemy.spellbook[spellchoice])
    
        def cast(self, enemy):
            if self.spellbook:
                spellchoice = randint(0, len(self.spellbook)-1)
                self.spellbook[spellchoice](self, enemy)
    
    >>> dm = DarkMage('Bad Guy')
    >>> p = Player('Do-Gooder')
    >>> p.spellsiphon(dm)
    >>> p.cast(e)
    Do-Gooder casted fireball on Evildoer for 10 damage
    >>> p.cast(dm)
    Do-Gooder casted fireball on Bad Guy for 10 damage
    

    您还可以在类之外定义静态方法,这样可以更轻松地在类之间共享它们,但我认为理想的方法是让拼写成为自己的 python 类,以便您可以附加名称以及他们的其他属性:

    class Fireball:
        name = 'fireball'
        damage = 10
    
        @classmethod
        def cast(cls, caster, target):
            print(
                '{} cast {} on {} for {} damage!'.format(
                    caster.name,
                    cls.name,
                    target.name,
                    cls.damage,
                )
           )
    
    class SuperFireball(Fireball):
        name = 'super fireball'
        damage = 50
    
    class Player:
        def __init__(self):
            self.spellbook = [Fireball]
    
        def list_spells(self):
            for spell in self.spellbook:
                print(spell.name)
    
        def cast(self, enemy):
            if self.spellbook:
                spellchoice = randint(0, len(self.spellbook)-1)
                self.spellbook[spellchoice].cast(self, enemy)
    

    【讨论】:

    • 这看起来可以处理我想做的所有事情——谢谢@Albert!
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多