python - 装饰器的继承
问题描述
我有 3 个文件1person.py
和.items.py
game.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
我已经进行了一些故障排除和编辑,但我无法确定太多。
解决方案
我认为你让事情变得比他们需要的复杂得多。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
直接使用,因为该方法是在类存在之前定义的(并且在任何实例存在之前很久)。
推荐阅读
- django - 使用 xlwt 将日期时间导出到 django 中的 excel
- r - 访问 group_by 数据集的第一行
- reactjs - 在渲染中循环遍历这个对象数组的正确方法是什么,做出反应
- highcharts - highcharts x轴类别不动态更新vuejs
- python - Numpy 2D 空间掩码用 2D 数组中的特定值填充以形成 3D 结构
- c++ - 可变参数函数中的参数解析
- swift - 如何从.mm调用swift?
- ios - Swift - Firebase - 朋友列表 - 创建朋友组的可能性
- .net - 使用 CloudWatch Events 和环境参数运行任务
- wordpress - WP Taxonomy - 元键名和元键值