1

我将如何格式化:

self.bot = servo.Robot({
        '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])

如果太多了,创建一个名为 self.bot 的变量,使其等于 self.Robot(servo_dict, num_list) 的返回值,它接受一个字典和一个列表作为参数。

我已经查看了PEP8其他Stack Overflow 问题。我会鼓励答案链接到样式指南...

4

1 回答 1

2

使用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])
于 2013-01-06T17:20:29.780 回答