Python 使用一类变量作为函数参数

Python 使用一类变量作为函数参数,python,python-3.x,Python,Python 3.x,我是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(n

我是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()
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
现在我知道我可以用

encounter(blue_slime.nom, blue_slime.hp, blue_slime.img)
但是我更愿意(并且认为这对于我的程序来说是必要的)只使用类名作为函数参数,然后在函数中我可以使用所有变量,而不必每次都写入它们。虽然这听起来像是懒惰,但我正在考虑让遭遇成为随机的,所以10%的几率遭遇(蓝色粘液)10%的几率遭遇(绿色粘液)

我觉得实现这一点最简单的方法是以某种方式将“class blue_slime”中的所有变量压缩成一个名称


请让我知道是否有办法做到这一点,也许我还没有学会

您只需将类传递到函数中,这就是您想要做的。这将解决您的问题:

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(nom, hp, img):
    print(char_name + " encountered a " + nom + "!!!")
    wait()
    while hp > 0:
        battle(hp, img)
    else:
        stats()
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

遭遇(某个怪物\u对象\u有\u名称\u hp\u和\u图像)
——似乎没问题。虽然类是一个对象,但如果创建和使用实例,代码可能会更成功。也许有两个大的蓝色黏液怪物!非常感谢您的详细回复。。。我将尝试将它们作为实例来实现,看看会发生什么!我真的很感激@user3186749如果您还不熟悉类和实例的概念,我建议您简要阅读一下。只要谷歌“类vs实例python”和上面的链接可能会有用。就像(只是谷歌搜索一下)它工作得很好,你是个巫师!是的,我在解读你的例子时读到了这个