使用dict
构造函数,您至少可以消除输入一堆引号:
self.bot = servo.Robot(dict(
waist = servo.Servo(3, 90, .02, 0),
shoulder = servo.Servo(4, 130, .03, 15),
elbow = servo.Servo(5, 110, .02, 19),
wrist = servo.Servo(6, 20, .01, 9),
claw = servo.Servo(7, 40, .01, 0)
), [5, 15, 25])
当然,你也可以像这样写一个辅助函数:
def servos(**kwargs):
for k, v in kwargs.iteritems():
kwargs[k] = servo.Servo(*v)
return kwargs
进而:
self.bot = servo.Robot(servos(
waist = (3, 90, .02, 0),
shoulder = (4, 130, .03, 15),
elbow = (5, 110, .02, 19),
wrist = (6, 20, .01, 9),
claw = (7, 40, .01, 0)
), [5, 15, 25])
如果您将使用不同类型的实例执行大量 dicts-of-instances,则可以使 helper 通用:
def instance_dict(typ, **kwargs):
for k, v in kwargs.iteritems():
kwargs[k] = typ(*v)
return kwargs
# later...
self.bot = servo.Robot(
instance_dict(servo.Servo,
waist = (3, 90, .02, 0),
shoulder = (4, 130, .03, 15),
elbow = (5, 110, .02, 19),
wrist = (6, 20, .01, 9),
claw = (7, 40, .01, 0) ),
[5, 15, 25])