来自dict的可更改函数调用

时间:2017-05-18 13:43:21

标签: python python-3.x

我是一个相对较新的人,拥有相当多的经验,而且我正在尝试进行基于文本的冒险,我正在建立一个战斗系统并希望拥有拥有相同数量的敌人不同的能力。我不是每次都为不同的敌人重建战斗,而是试图为每个敌人使用可互换的词典。我的目标是创建一个函数调用,该函数调用根据战斗中的敌人而不会进入对象而变化。我在下面有一个例子,想知道是否有办法做类似的事情。

wolf = {'ability': 'bite'}
bear = {'ability': 'claw'}
enemy = {}

def claw():
    print('stuff')

def bite():
    print('different stuff')

def use_ability():
    enemy = wolf
    enemy['ability']()

use_ability()

3 个答案:

答案 0 :(得分:5)

在python函数中是第一类对象。您可以将它们用作词典中的值。

wolf = {'ability': bite}
bear = {'ability': claw}

但是要小心,因为python中没有前向引用。因此,在将它们分配给字典之前,请确保定义函数。

def claw():
    print('stuff')

def bite():
    print('different stuff')

wolf = {'ability': bite}
bear = {'ability': claw}

def use_ability():
    enemy = wolf
    enemy['ability']()

use_ability()

答案 1 :(得分:2)

你可以这样做:

def claw():
    print('stuff')

def bite():
    print('different stuff')

wolf = {'ability': bite}
bear = {'ability': claw}

def use_ability(enemy):
    enemy['ability']()

use_ability(wolf)
# different stuff

但这并不意味着你应该这样做。

使用面向对象的编程。如果您只想使用dicts和函数,则可能应该编写Javascript。

答案 2 :(得分:2)

我无法帮助自己,而是制作一个小程序来解释如何以面向对象语言完成

  

你应该查阅OOP-Languages如何工作的一些指南,因为在制作游戏时,如果你这样做会很有帮助

     

http://www.python-course.eu/object_oriented_programming.php

# This is the SUPERCLASS it holds functions and variables 
# that all classes related to this object use
class Enemy(object):
    # Here we initialise our Class with varibales I've given an example of how to do that
    def __init__(self, HP, MAXHP, ability):
        self.HP = HP
        self.MAXHP = MAXHP
        self.ability = ability

    # This function will be used by both Bear and Wolf!
    def use_ability(self):
        print(self.ability)

# This is our Wolf Object or Class
class Wolf(Enemy):
    # Here we init the class inheriting from (Enemy)
    def __init__(self, ability, HP, MAXHP):
        super().__init__(HP, MAXHP, ability)

    # Here we call the superfunction of this Object.
    def use_ability(self):
        super().use_ability()

# Same as Wolf
class Bear(Enemy):
    def __init__(self, ability, HP, MAXHP):
        super().__init__(HP, MAXHP, ability)

    def use_ability(self):
        super().use_ability()

# How to init Classes
wolf_abilities = 'bite'
w = Wolf(wolf_abilities, 10, 10)

bear_abilities = 'claw'
b = Bear(bear_abilities, 10, 10)

# How to use methods from Classes
b.use_ability() # This will print 'bite'
w.use_ability() # This will print 'claw'