python - 从其属性引用对象
问题描述
我有一个类来创建一个播放器:
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 可能有点棘手......
谢谢,
解决方案
你可以试试这个:
def take_damage(self, damage):
self.health = max(self.health - damage, 0)
if self.HP == 0:
print("{} dies....".format(self.pl_id))
raise Dead
推荐阅读
- docker - jenkins管道中docker gcloud容器内的kubectl问题
- macos - 如何在 macOS 命令行工具中启用框架本地化?
- r - 在空格处拆分 R 字符串,但在空格位于单引号之间时不拆分
- python - urllib python3中的POST请求
- c - 读取不同地址的字符串后指向的值发生变化
- botframework - 如何在技能之间切换上下文?
- javascript - 用于获取我在工作表上的一个文件中输入的信息并将其设为数组的代码,以便我可以将其传输到另一张工作表(不同的 ID)
- python - 使用 Dask 分部高效读取大型 csv 文件
- r - rticles 包中的 knitr::include_graphics 不起作用
- ios - 如何在 AppDelegate 中使用 TabbarController 在 SWRevealViewController 上呈现 ViewController