【发布时间】:2019-01-02 18:47:32
【问题描述】:
我正在尝试编写一个函数装饰器来测试 x、y 的边界
#this is my bound test function
def boundtest(func):
def onDecorator(self, x, y, *args, **kwargs):
print(x, y, *args, **kwargs)
assert x in range(self.width) and y in range(self.height)
return func(x, y, *args, **kwargs)
return onDecorator
class Game:
#these are the functions that need bound checking
@boundtest
def at(self, x: int, y: int) -> int:
return self.map[x, y]
@boundtest
def set(self, x: int, y: int, data):
self.map[x, y] = data.value
当我执行game.set(1, 1, Color.RED) 时,我得到:
Traceback (most recent call last):
File "C:\Users\Ben\Desktop\Projects\bubble-breaker-bot\game.py", line 61, in <module>
game.set(1, 1, Color.RED)
File "C:\Users\Ben\Desktop\Projects\bubble-breaker-bot\game.py", line 21, in onDecorator
return func(x, y, *args, **kwargs)
TypeError: set() missing 1 required positional argument: 'data'
我需要 boundtest 函数来检查 x 和 y 是否分别在 self.width 和 self.height 的范围内,同时能够将任意数量的参数传递给它正在装饰的函数。
为什么会这样?
【问题讨论】:
标签: python python-3.x decorator python-decorators