Python 动态属性值绑定到方法
Python dynamic attribute value bind to method
在阅读了这里的几篇文章后,我仍然对以函数作为值来实现 Class 动态属性的正确方法感到困惑。
我接触 python 已经有一段时间了,现在我有点卡住了。
我有以下 class:
class RunkeeperUser(object):
def __init__(self, master):
self.master = master
# Get the user methods and set the attributes
for user_method, call in self.master.query('user').iteritems():
# Should not get the value but bind a method
setattr(
self,
user_method,
self.master.query(call)
)
def get_user_id(self):
return self.user_id
def query(self, call):
return self.master(call)
现在正如您所见,在设置属性时它会直接执行 self.master.query(调用),并且在访问属性时结果已经存在。
问题是如何使这个属性值在运行时动态且尚未执行?
我试过:
setattr(
self,
user_method,
lambda: self.master.query(call)
)
但由于某种原因,这并不能很好地工作。任何 help/guidance 或最佳原则来实现所描述的结果?
这是一个众所周知的问题。您必须在 lambda 中绑定参数的当前值,即:
setattr(
self,
user_method,
lambda call=call: self.master.query(call)
)
在阅读了这里的几篇文章后,我仍然对以函数作为值来实现 Class 动态属性的正确方法感到困惑。
我接触 python 已经有一段时间了,现在我有点卡住了。
我有以下 class:
class RunkeeperUser(object):
def __init__(self, master):
self.master = master
# Get the user methods and set the attributes
for user_method, call in self.master.query('user').iteritems():
# Should not get the value but bind a method
setattr(
self,
user_method,
self.master.query(call)
)
def get_user_id(self):
return self.user_id
def query(self, call):
return self.master(call)
现在正如您所见,在设置属性时它会直接执行 self.master.query(调用),并且在访问属性时结果已经存在。
问题是如何使这个属性值在运行时动态且尚未执行?
我试过:
setattr(
self,
user_method,
lambda: self.master.query(call)
)
但由于某种原因,这并不能很好地工作。任何 help/guidance 或最佳原则来实现所描述的结果?
这是一个众所周知的问题。您必须在 lambda 中绑定参数的当前值,即:
setattr(
self,
user_method,
lambda call=call: self.master.query(call)
)