我不知道这是否会是有意义的,但是......映射obj.method({参数:值})到obj.argument(值)
我试图动态分配方法的目的。
#translate this
object.key(value)
#into this
object.method({key:value})
要在我的例子更具体的,我有一个对象(我没有写),让我们把它叫做电机,其中有一些通用的方法来设置,状态和其他几个人。有些人拿字典作为参数,有些人拿一份清单。来改变电机的速度,并观察结果,我使用:
motor.set({'move_at':10})
print motor.status('velocity')
马达对象,则格式化该请求为JSON-RPC字符串,并将其发送到IO守护进程。 python马达对象不关心参数是什么,它只是处理JSON格式和套接字。字符串move_at和velocity只是数百个有效参数中的两个。
我希望做的是不要使用以下:
motor.move_at(10)
print motor.velocity()
我希望做一个通用的方法,因为我有这么多不同的参数,我们可以通过。我不希望做的是:
# create a new function for every possible argument
def move_at(self,x)
return self.set({'move_at':x})
def velocity(self)
return self.status('velocity')
#and a hundred more...
我做了这个这表明解决一些搜索在于lambda表达式和元编程,两个主题我一直无法左右我的头。
UPDATE:
基于从user470379代码我想出下面...
# This is what I have now....
class Motor(object):
def set(self,a_dict):
print "Setting a value", a_dict
def status(self,a_list):
print "requesting the status of", a_list
return 10
# Now to extend it....
class MyMotor(Motor):
def __getattr__(self,name):
def special_fn(*value):
# What we return depends on how many arguments there are.
if len(value) == 0: return self.status((name))
if len(value) == 1: return self.set({name:value[0]})
return special_fn
def __setattr__(self,attr,value): # This is based on some other answers
self.set({attr:value})
x = MyMotor()
x.move_at = 20 # Uses __setattr__
x.move_at(10) # May remove this style from __getattr__ to simplify code.
print x.velocity()
输出:
Setting a value {'move_at': 20}
Setting a value {'move_at': 10}
10
谢谢大家谁帮助!
BTW,根据问题的描述,应该不是“#translate this”和“#into这个”顶部的描述被逆转? (将object.key(value)转换为object.method({key:value})) – user470379 2011-01-27 19:02:40
@ user470379,是的,你是对的。 – RyanN 2011-01-27 20:04:52