如何使用另一个 class 引用一个 class 的属性

How to reference an attribute from one class using another class

这是我的代码

import random

class Player_Character:
    def __init__(self, hp, maxhp, ac, THAC0):
        self.hp = int(hp)
        self.maxhp = int(maxhp)
        self.ac = int(ac)
        self.THAC0 = int(THAC0)
    def attack(goblin):
        Player_Character_Damage = random.randint(1,10)
        goblin.hp -= Player_Character_Damage
        if (goblin.hp <= 0):
            print("congratulations you killed the goblin")
            del goblin

class goblin:
    def __init__(self, hp, maxhp, ac, THAC0):
        self.hp = int(hp)
        self.maxhp = int(maxhp)
        self.ac = int(ac)
        self.THAC0 = int(THAC0)
    def attack(Player_Character):
        goblin_damage = random.randint(1,4)
        Player_Character.hp -= goblin_damage
        if (Player_Character.hp <= 0):
            print("oh dear you have died")
            del Player_Character


Player_Character(10, 20, 10, 15)
goblin(5, 10, 8, 18)

Player_Character.attack(goblin)

我希望 Player_Character.attack(goblin) 对 goblin 造成 1-10 点伤害(可能会杀死它)但是我得到一个错误:AttributeError: type object 'goblin' has no attribute 'hp'...显然我创建了 class 具有 'hp' 属性,现在很困惑。

你必须实例化对象

正如@ShadowRanger 在评论中解释的那样,我应该提到我将 self 添加到函数中

import random

class Player_Character:
    def __init__(self, hp, maxhp, ac, THAC0):
        self.hp = int(hp)
        self.maxhp = int(maxhp)
        self.ac = int(ac)
        self.THAC0 = int(THAC0)
    def attack(self, goblin):
        Player_Character_Damage = random.randint(1,10)
        goblin.hp -= Player_Character_Damage
        if (goblin.hp <= 0):
            print("congratulations you killed the goblin")
            del goblin

class goblin:
    def __init__(self, hp, maxhp, ac, THAC0):
        self.hp = int(hp)
        self.maxhp = int(maxhp)
        self.ac = int(ac)
        self.THAC0 = int(THAC0)
    def attack(self, Player_Character):
        goblin_damage = random.randint(1,4)
        Player_Character.hp -= goblin_damage
        if (Player_Character.hp <= 0):
            print("oh dear you have died")
            del Player_Character


p = Player_Character(10, 20, 10, 15)
g = goblin(5, 10, 8, 18)


p.attack(g)

@ShadowRanger 也提到 del 没有按预期工作,您可以在外部使用它来删除实例。

p = Player_Character(10, 20, 10, 15)
g = goblin(5, 10, 8, 18)

p.attack(g)

if(g.hp <= 0):
    print("congratulations you killed the goblin")
    del g