我想创造一个命令命令,该命令接受一个参数以使用消耗品(这是一个文本库)
import cmd
class Adventure(cmd.Cmd):
prompt = ">"
# Other commands cut out because they are not part of the problem
def do_use(self, arg):
arg.use(pc)
其中arg将是消耗品类的对象,具有自用(target)函数之前已经在代码中定义过(在本例中,是药剂对象)
class Consumable:
def __init__(self, hpgain):
self.hpgain = hpgain
def use(self, target):
inventory.remove(self)
target.addhp(self.hpgain)
potion = Consumable(5)
inventory = []
inventory.append(potion)
而pc是玩家类的对象,其具有self.addhp文件(amount)函数已在代码中定义
class Player:
def __init__(self, hp):
self.hp = hp
self.maxhp = hp
def addhp(self, amount):
self.hp += amount
if self.hp > self.maxhp:
self.hp = self.maxhp
pc = Player(20)
两者都药剂使用(pc)和pc.addhp公司(amount)函数在标准Python shell中工作
当我尝试在自定义shell中使用药剂对象类型使用药剂时,出现以下错误:
Traceback (most recent call last):
File "C:\Users\[Redacted]\Desktop\adventure.py", line 225, in <module>
Adventure().cmdloop()
File "C:\Python37\lib\cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "C:\Python37\lib\cmd.py", line 217, in onecmd
return func(arg)
File "C:\Users\[Redacted]\Desktop\adventure.py", line 199, in do_use
arg.use(pc)
AttributeError: 'str' object has no attribute 'use'
因此,它将函数的参数视为字符串而不是对象。我该怎么改变呢?你知道吗
Cmd模块将每个参数解析为一个命令行参数,在本例中它是一个字符串。在Python中,有几种方法可以按名称查找当前加载到内存中的
objects
。globals
就是其中之一。如果您试图定位的对象恰好在另一个模块中声明,即(x=5
),那么我们可以使用getattr(module_name, var_name)
!你知道吗让我知道这是否有效!你知道吗
我将创建一个
Inventory
类,如下所示:do_use
方法不是线程安全的,因此如果您在任意点添加不同的线程,请记住您应该在某个地方添加并使用锁。你知道吗相关问题 更多 >
编程相关推荐