对函数argumen使用一类变量

2024-05-23 17:11:30 发布

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

我是python新手,大约3天,我不确定我是否正确地表达了这个问题

我有一门课:

class blue_slime:
    nom = "BLUE SLIME"
    img = "  /\ \n( o o)"
    str = 10
    int = 5
    dex = 5
    con = 10
    spd = 10
    hp = ((con + str) / 2)
    mp_bonus = 1

我想在另一个函数中使用这个类的变量

def encounter(nom, hp, img):
    print(char_name + " encountered a " + nom + "!!!")
    wait()
    while hp > 0:
        battle(hp, img)
    else:
        stats()

现在我知道我可以用

encounter(blue_slime.nom, blue_slime.hp, blue_slime.img)

但是我更希望(我的程序可能需要这样做)能够使用类名作为函数参数,然后在函数中我可以使用所有变量,而不必每次都写它们。虽然这听起来像是懒惰,但我正在考虑让遭遇成为随机的,所以10%的几率遭遇(蓝色粘液)10%的几率遭遇(绿色粘液)

我觉得实现这一点最简单的方法就是将“class blue\u slime”中的所有变量压缩成一个名称

如果有办法的话请告诉我,也许我还没学会


Tags: 函数imgblueconnomclasshp新手
1条回答
网友
1楼 · 发布于 2024-05-23 17:11:30

你可以把类传递到函数中,这就是你想做的。这将解决您的问题:

def encounter(monster):
    monster.hp
    monster.img
    # etc.

以下是一些提示:

正如在您的问题的评论中已经提到的,您可能希望使用这些类的实例,而不是实际的类。我将给出一个示例类,其中包含一些指针:

class BlueSlime: # Using CapCase like this is normal for class names
    # You can use this space to make class variables.
    # These will be the same across all the classes.
    # Probably use this for initializing your instances
    base_hp = 5
    base_int = 10
    base_dmg = 3

    def __init__(self): # The "Constructor" of your instances
        self.current_hp = self.base_hp # self refers to the instances
        self.int = self.base_int
        self.dmg = self.base_dmg

这个例子很好,因为如果你的一些粘液服用dmg,你不一定希望他们都服用dmg

bs1 = BlueSlime() # Init the instance
bs2 = BlueSlime()

# bs1 takes 1 dmg (May want a method to do this)
bs1.hp -= 1

bs1.hp
# Now 4

bs2.hp
# Still 5

回到您的问题,此时,您可以将这些实例传递到遭遇函数中

def encounter(monster):
    # Something happens here to reduce the hp, it will reduce the instance's hp

    # Something happens here to deal dmg, you can look it up on the instance
    player.hp -= monster.dmg # Something like this....
    # etc

相关问题 更多 >