Python 如何将自定义函数添加到每个对象不同的类中?

Python 如何将自定义函数添加到每个对象不同的类中?,python,Python,我试图让它在使用某个项目时触发某个函数,但我不知道该如何做。我在找一些类似于 class Item(object): def __init__(self, quantity, name, description, effect): #effect is in code and used by the computer, not shown to the player. self.quantity=quantity self.name=name self.descrip

我试图让它在使用某个项目时触发某个函数,但我不知道该如何做。我在找一些类似于

class Item(object):
  def __init__(self, quantity, name, description, effect): #effect is in code and used by the computer, not shown to the player.
    self.quantity=quantity
    self.name=name
    self.description=description
    self.effect=effect
def useitem(Item):
  if Item.quantity>0:
    Item.quantity-=1
    Item.effect
但是,当然,这是行不通的。 我该怎么做


我的编码知识非常有限,因此如果您能详细解释一下您正在做什么,那就太好了。

阅读有关lambda的文档。此外,您还可以使用不带参数的函数,因为它们与Python中的其他对象一样。请注意提高可读性:前后运算符,例如-=应该有一个空格。我有点迷路了。这如何让我的健康增加20?而且,如果我把它放在useitem函数下,我如何改变它,比如说,一个医疗套件会增加50个健康值?很可能你会有另一个类,比如PlayerCharacter,它会有一个健康属性,而这个类实际上会有一些方法,比如acquire\u item和use item。然后我们可以继续实现这些方法。要产生不同的效果,您只需在效果参数中使用不同的参数初始化对象。我创建了函数Item.useitem,它下面的代码与文章中的useself相同。然而,当我运行它的时候,它的健康状况并没有改变,它是在10,并且在使用它后保持在10。你能解释一下这个效果是如何作为字符串作用于变量health的吗?
  bandaid=Item(1, "band-aid", "helps with cuts", health+=20)
class Item(object):
    def __init__(self, quantity, name, description, effect): 
        self.name=name
        self.description=description
        self.effect= 'self.' + effect

class Player():
    def __init__(self):
        self.health = 100
        self.inventory = {}
    def get_item(self, item):
        if item in self.inventory:
            self.inventory[item] += 1
        else: self.inventory[item] = 1
    def use_item(self, item):
        if self.inventory[item] and self.inventory[item] > 0:
            self.inventory[item]-=1
            exec(item.effect)

p1 = Player()
bandaid=Item(1, "band-aid", "helps with cuts", 'health += 20')
p1.get_item(bandaid)
p1.use_item(bandaid)
print(p1.health)