我正在try 制作一个基于文本的RPG.我有一些代码,比如:

英雄.py:

class Hero():
   def __init__(self):
      pass
   def Attack(self, target):
      # ...
   def TakeDamage(self, amount):
      # ...

怪物.py:

class Monster():
   def __init__(self):
      pass
   def Attack(self, target):
      # ...
   def TakeDamage(self, amount):
      # ...

整个文件 struct 如下所示:

|__ backend
    __init__.py
    monsters.py
    heroes.py
MainGame.py

假设我想要MonsterHero访问彼此的AttackTakeDamage函数,例如:

class Monster():
   def __init__(self):
      pass
   def Attack(self, target):
      # ...
   def TakeDamage(self, amount, target:Hero):
      damage = # damage calculation here
      target.TakeDamage(damage)

我该怎么做?到目前为止,我已经try 过:

  • 在各自的文件中相互导入(例如from .monsters import Monster)-这会导致读取ImportError: cannot import name 'Monster' from partially initialized module 'backend.monsters' (most likely due to a circular import)时出错.

推荐答案

Broadly speaking, classes don't have methods; instances do. The purpose of a class is to define a data type. You don't need to see that definition, in Python, in order to use instances.

考虑Monster类中的代码:

   def TakeDamage(self, amount, target:Hero):
      damage = # damage calculation here
      Hero.TakeDamage(damage)

(我暂时忽略这里的逻辑可能没有那么有道理.)

:Hero是一个提示-给阅读代码的人,可能还有第三方工具;Python本身does not care——target将是Hero类的一个实例.

我们想在那个实例上调用一个方法,在类上调用not.doesn't have a TakeDamage类方法;它只有一个TakeDamage-function,用于创建方法when we look it up via an instance.

因此,代码not应该是Hero.TakeDamage(damage).应该是target.TakeDamage(damage),因为targetHero实例的名称,我们将调用其方法.

为此,我们对Hero类的定义进行了解释.monsters.py should not import任何事情都可以让这一切顺利.

When the code is running, at the moment that the method call is attempted,Python将判断名为target的对象是否具有TakeDamage属性.当它没有找到直接连接到实例的函数时,它将在类中查找,并在该类中找到TakeDamage函数.它将自动从中创建一个方法.然后它会判断从这个过程中得到的TakeDamage是否可以调用(扰流板:是的,因为它是一个方法),然后调用它.

Python相关问答推荐

Python 约束无法解决n皇后之谜

可变参数数量的重载类型(args或kwargs)

将图像拖到另一个图像

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

如何过滤包含2个指定子字符串的收件箱列名?

基于字符串匹配条件合并两个帧

在np数组上实现无重叠的二维滑动窗口

梯度下降:简化要素集的运行时间比原始要素集长

下三角形掩码与seaborn clustermap bug

使用__json__的 pyramid 在客户端返回意外格式

如果有2个或3个,则从pandas列中删除空格

GPT python SDK引入了大量开销/错误超时

如何训练每一个pandaprame行的线性回归并生成斜率

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

Matplotlib中的曲线箭头样式

函数()参数';代码';必须是代码而不是字符串

如何在Python中画一个只能在对角线内裁剪的圆?

使用元组扩展字典的产品挑战

使用Django标签显示信息

如何从NumPy数组中提取主频?