在Python中级联可选参数

Com*_* 10 1 python optional-parameters

我有一系列可以通过可选地传递参数来创建的类,或者如果省略,它将使用默认数据结构.所有类都以相同的方式工作,因此:

class square(object):
    _vertices = [ (0, 0), (0, 10), (10, 10), (10, 0) ]
    def __init__(self, vertices=_vertices):
        # more stuff ...

class triangle(object):
    _vertices = [ (0, 0), (5, 10), (10, 10) ]
    def __init__(self, vertices=_vertices):
        # more stuff ...

# ... more classes
Run Code Online (Sandbox Code Playgroud)

我还有一个工厂函数,它接受一个字符串并创建一个合适的对象

def create_shape(key)
    if key == 'square':
       return square()
    elif key == 'triangle':
       return triangle()
Run Code Online (Sandbox Code Playgroud)

虽然很自然,但这不允许我传递顶点参数

shape1 = create_shape('square') # OK, basic creation
shape2 = create_shape('triangle', my_own_vertices) # Not OK, param 2
                                                   # can't go through factory
Run Code Online (Sandbox Code Playgroud)

我绕道而行是按照以下方式修饰工厂,但对我来说,这似乎是一种非常笨拙的事情.

def create_shape(key, vertices=None):
    if key == 'square':
        return square(vertices) if vertices else square()
    elif key == 'triangle':
        return triangle(vertices) if vertices else triangle()
Run Code Online (Sandbox Code Playgroud)

本质上,我只想通过一个可选参数,而不需要顶层(create_shape)知道默认值应该是什么.这样做有更清晰/更简单/更pythonic的方法吗?我看过其他问题/答案,但似乎没有比上面更好的了.

小智 5

如果要将可选参数传递给函数,可以使用**kwags

def create_shape(key, **kwargs):
    if key == 'square':
        return square(**kwargs)
    elif key == 'triangle':
        return triangle(**kwargs)
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样调用您的工厂功能.

create_shape('triangle', vertices = [( 0,0), (1, 10)])
Run Code Online (Sandbox Code Playgroud)

Triangle类的init函数将接收新的顶点值.