首页 > 解决方案 > 装饰器的继承

问题描述

我有 3 个文件1person.py和.items.pygame.py

其中game.py有一个事件处理程序,当按下按钮或空间时,它会调用玩家对象以使用他手中的对象赋予它的功能。

为了实现这一点,我创建了一个可继承的项目类,该类具有一个函数,当人们调用该函数时,该函数返回一个特定于项目子类的函数。

我试图创建一个 item 的装饰器函数,@efunc它将下面的函数设置为 of 的变量self.efunc和第二个函数,由 personinhand.getefunc()调用,该函数将 efunc 作为变量返回,然后在 game.py 调用该函数时由 person 调用。

person.py

class person:
  def init(self):

    self.inhand = banana # this could be many other different items and
    #changes through the game

  def useefunc(self): # game.py calls this function when e is pressed
    func = self.inhand.getefunc()
    func(self)

  def usespacefunc(self):# game.py calls this function when space is #pressed
    func = self.inhand.getspacefunc()
    func(self)

items.py

class items:
  def init(self):
    self.efunc
    self.spacefunc

  def efunc(func,self):
    self.efunc = func

  def getefunc(self)
    return self.efunc

  def spacefunc(func,self):
    self.spacefunc = func

  def getspacefunc(self):
    return self.spacefunc

class banana(items):

  def init(self):# was removed
    self.efunc = consume # I tried this it did not work was removed
    self.spacefunc = trash # also did not work was removed
  @spacefunc
  def consume (p):

#p is a person so consume can transfer its effects on the person and its animation
 @efunc
  def trash(p):

class nothing(items):
  pass

我已经进行了一些故障排除和编辑,但我无法确定太多。

标签: pythonfunctioninheritance

解决方案


我认为你让事情变得比他们需要的复杂得多。Person对象将自己的引用传递给其手中项目的适当方法会容易得多。

class Person:
    def __init__(self, in_hand):
        self.in_hand = in_hand

    def use_object(self):
        self.inhand.use(self)

class Item:
    def use(self, person):
        pass

class Banana(Item):
    def use(self, person):
        # do something here?

不需要装饰器或任何其他复杂性。

至于为什么您的代码不起作用,主要问题是您试图self在还没有实例的上下文中使用。例如,方法的装饰器不能self直接使用,因为该方法是在类存在之前定义的(并且在任何实例存在之前很久)。


推荐阅读