首页 > 解决方案 > 从其属性引用对象

问题描述

我有一个类来创建一个播放器:

class player:

# Method to create object (Constructor)
    def __init__(self, pl_id, alive = True, health = 100):

        self.pl_id = pl_id
        self.alive = alive
        self.health = health

然后我有一个提供唯一 ID 的外部接口。我从这个 id 创建一个播放器

def create_player(myInterface):

    # Get user attributes
    user = myInterface.unique_user

    print('Hello {}'.format(user['name']))

    myPlayer = player(user['id'])

我需要能够通过它的 id 引用 myPlayer 以用于接口中的未来功能,例如

def take_damage(myInterface):

    user = myInterface.unique_user

    damage = myInterface.damage

我将在游戏中有多个玩家,我希望能够做这样的事情:

    myPlayer.health = myPlayer.health - damage

但是我看不到如何引用哪个播放器应该接收该功能。我是否应该动态命名 myPlayer 以包含 user_id。这是不好的做法吗?这是对类的正确使用吗?

myInterface 实际上来自另一个包(python-telegram-bot),所以编辑 myInterface 可能有点棘手......

谢谢,

标签: pythonclassoop

解决方案


你可以试试这个:

    def take_damage(self, damage):
        self.health = max(self.health - damage, 0)
        if self.HP == 0:
            print("{} dies....".format(self.pl_id))
            raise Dead

推荐阅读