gpt4 book ai didi

python - 如何使用 Python 装饰器处理 'self' 参数

转载 作者:太空宇宙 更新时间:2023-11-03 11:11:18 24 4
gpt4 key购买 nike

我正在尝试设置一些装饰器,以便我可以执行以下操作:

class Ball(object):
def __init__(self, owner):
self.owner = owner

class Example(CommandSource):
@command
@when(lambda self, ball: ball.owner == self)
def throwBall(self, ball):
# code to throw the ball
pass

e = Example()
ball = Ball(e)
commands = e.listCommands(ball) # commands = [ 'throwBall' ]

这目前不起作用,因为当调用验证 lambda 时,没有传递 self 参数。

现在这样的东西可以正常工作了:

class Example(CommandSource):
@command
@when(lambda ball: ball.is_round)
def throwBall(self, ball):
pass

但这也行不通:

class Example(CommandSource):
def verify_owner(self, ball):
return ball.owner == self

@command
@when(verify_owner)
def throwBall(self, ball):
pass

目的是能够将类中的方法标记为“命令”,并获取可有效运行的命令列表。实际上运行该方法并没有改变。我想在这里使用装饰器,因为这似乎是最不笨拙的方法。实际上,我正在尝试使用 Python 设置一些 DSL。

但我遇到了困难,尤其是在 self 参数方面。这是我当前对 commandwhenCommandSource 的实现:

def command(cmd):
if getattr(cmd, 'command', False): return cmd

def wrapper(*args, **kwargs):
return cmd(*args, **kwargs)

wrapper.validators = []
wrapper.command = True

return wrapper

def when(predicate):
def createCommand(cmd):
newcmd = command(cmd)
newcmd.validators.append(predicate)
return newcmd
return createCommand

class CommandSource(object):
def listCommands(self, *args, **kwargs):
commands = []
for command in dir(self.__class__):
func = getattr(self, command, None)

if func == None or getattr(func, 'command', False) == False:
continue
valid = True
for validator in func.validators:
if not validator(*args, **kwargs):
valid = False
break
if valid:
commands.append(command)
return commands

最佳答案

如下更改您的 CommandSource:

class CommandSource(object):

def listCommands(self, *args, **kwargs):
commands = []
for command in dir(self.__class__):
func = getattr(self, command, None)
if func == None or getattr(func, 'command', False) == False:
continue
for validator in func.validators:
if not validator(self, *args, **kwargs):
break
else:
commands.append(command)
return commands

并使用您的第一个代码。

关于python - 如何使用 Python 装饰器处理 'self' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2546801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com