You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何独立编辑多个相同类实例的属性数据?

问题:Enemy实例属性无法独立修改

我定义了Enemy基类与Orc子类,并实例化一个Orc对象加入enemies列表:

class Enemy:
    def __init__(self, health, defence, strength, name, currenthealth, image):
        Enemy.health = health
        Enemy.defence = defence
        Enemy.strength = strength
        Enemy.name = name
        Enemy.currenthealth = currenthealth
        Enemy.image = image

class Orc(Enemy):
    def __init__(self, health, defence, strength, name, currenthealth, image):
        super().__init__(health, defence, strength, name, currenthealth, image)

orc = Orc(10, 5, 5, "Orc", 10, Orcimg)
enemies.append(orc)

随后通过randomencounter函数将该实例多次添加到displayset列表中(最多4次,对应4个独立敌人):

def randomencounter(enemies) :
    numofopps = random.randint(1, 4)
    enemyset = []
    displayset =  []
    x = 0
    pygame.display.update()
    while x != (numofopps):
        enemyset.append(str((enemies[0].name)))
        displayset.append(enemies[0])
        time.sleep(0.5)
        x = x + 1
    return displayset, enemyset, numofopps

当尝试独立编辑这些实例时,修改其中一个的health属性(比如减去6),其他实例的health会同步变更。期望无需创建多个不同变量就能独立编辑列表中各实例的数据,尝试列表索引操作无效,寻求可行解决方法。

相关目标选择代码如下:

pygame.display.update()
for event in pygame.event.get():
    if len(displayset) == 3:
        if (((displayset[2].image).get_rect(center=((1320 + (0.5 * Imagex[2])),(300+ (0.5 * Imagey[2]))))).collidepoint(pygame.mouse.get_pos()) == True) and Imagex[2] != None:
            print("3")
            Leftbutton, NUL2, NUL3 = pygame.mouse.get_pressed(num_buttons=3)
            if Leftbutton == True:
                return displayset[2], 2
                GGG = 1
        elif ((((displayset[1].image).get_rect(center=((920 + (0.5 * Imagex[1])),(300+ (0.5 * Imagey[1]))))).collidepoint(pygame.mouse.get_pos())) == True) and Imagex[1] != None:
            print("2")
            Leftbutton, NUL2, NUL3 = pygame.mouse.get_pressed(num_buttons=3)
            if Leftbutton == True:
                return displayset[1], 1
                GGG = 1
        elif ((displayset[0].image).get_rect(center=((520 + (0.5 * Imagex[0])),(300+ (0.5 * Imagey[0])))).collidepoint(pygame.mouse.get_pos()) == True) and Imagex[0] != None:
            print("1")
            Leftbutton, NUL2, NUL3 = pygame.mouse.get_pressed(num_buttons=3)
            if Leftbutton == True:
                return displayset[0], 0
                GGG = 1

(注:死亡判定代码存在符号错误,此问题可自行修复)


解决方法

1. 修复Enemy类的属性绑定错误

你的Enemy类把属性赋值给了类本身(Enemy.health = health),这会导致所有实例共享同一个类属性,而非每个实例拥有独立的实例属性。正确写法是用self绑定实例属性:

class Enemy:
    def __init__(self, health, defence, strength, name, currenthealth, image):
        self.health = health  # 用self替代Enemy,将属性绑定到当前实例
        self.defence = defence
        self.strength = strength
        self.name = name
        self.currenthealth = currenthealth
        self.image = image

class Orc(Enemy):
    def __init__(self, health, defence, strength, name, currenthealth, image):
        super().__init__(health, defence, strength, name, currenthealth, image)

2. 生成独立的Orc实例

即使修复了Enemy类,原randomencounter函数仍是重复添加同一个Orc实例到displayset。要实现独立敌人,需每次创建新的Orc实例:

def randomencounter(enemies) :
    numofopps = random.randint(1, 4)
    enemyset = []
    displayset =  []
    x = 0
    pygame.display.update()
    # 从模板实例中获取参数,每次创建新实例
    base_orc = enemies[0]
    while x != numofopps:
        new_orc = Orc(base_orc.health, base_orc.defence, base_orc.strength, base_orc.name, base_orc.currenthealth, base_orc.image)
        enemyset.append(new_orc.name)
        displayset.append(new_orc)
        time.sleep(0.5)
        x += 1
    return displayset, enemyset, numofopps

3. 简化实例复制(可选)

如果不想手动传递所有参数,可使用copy模块直接复制实例:

import copy

def randomencounter(enemies) :
    numofopps = random.randint(1, 4)
    enemyset = []
    displayset =  []
    x = 0
    pygame.display.update()
    while x != numofopps:
        # 深拷贝原实例生成独立新实例
        new_orc = copy.deepcopy(enemies[0])
        enemyset.append(new_orc.name)
        displayset.append(new_orc)
        time.sleep(0.5)
        x += 1
    return displayset, enemyset, numofopps

修改后,displayset中的每个Orc实例都是独立个体,修改其中一个的属性不会影响其他实例。


内容的提问来源于stack exchange,提问作者DDA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:56:36