我想将此类构造为方法+参数,然后以相同的方式调用该方法。
class Event(object):
def __init__(self, method, *args):
self.method = method
if len(args) == 0:
self.args = None
else:
if len(args) == 1:
if args[0]:
self.args = args[0]
else:
self.args = None
elif len(args) >= 2:
self.args = list(args)
def __call__(self, handlers):
obj = handlers[self.key]
fn = getattr(obj, self.method)
if self.args:
if type(self.args) is list:
fn(*self.args)
else:
fn(self.args)
else:
fn()
在大多数情况下它都能正常工作:
SystemEvent('add_player', player.name, player.faction)
但如果其中一个参数应该是一个列表,它会失败,如下所示:
class Game:
def move_agent(self, waypoints):
#for step in waypoints:
GameEvent('move_agent', [(1,1),(2,2),(3,3)])
...
TypeError: move_agent() takes exactly 2 arguments (3 given)
基本上,我希望能够在构造函数中放置任何格式的参数,并让它们以相同的方式调用目标函数。
答案 0 :(得分:0)
我不明白为什么你需要转换收到的args
。为什么不简单:
class Event(object):
def __init__(self, method_name, *args):
self.method_name = method_name
# Store args unconditionally.
self.args = args
def __call__(self, obj):
# Now you can always use *self.args without checking its type.
getattr(obj, self.method_name)(*self.args)
class A(object):
def method(self, args):
print(args)
a = A()
Event('method', [1, 2, 3])(a)
答案 1 :(得分:0)
将参数传递为
GameEvent('move_agent', [((1,1),(2,2),(3,3))])
它将作为单个元组。你不需要传递三个不同的元组作为参数。