简体   繁体   English

尝试创建从Python列表继承的类时语法无效

[英]invalid syntax on attempting to create a class that inherits from Python list

I am creating a small class that inherits from a Python list. 我正在创建一个从Python列表继承的小类。

class palette(list):

    def __init__(
        self,
        *args,
        name   = None, # string name
        colors = None, # list of colors
        ):
        super().__init__(self, *args)   
        self._name   = name
        self.extend(colors)

When I run this, I get a syntax error at the name argument of the initialisation function. 运行此命令时,在初始化函数的name参数处收到语法错误。 Why is this? 为什么是这样? How can I fix it? 我该如何解决? I am working with both Python 2 and 3. 我正在使用Python 2和3。

*args must come after the other arguments, not before or in the middle of them. *args必须来自其他参数之后 ,而不是之前或在他们中间。 (At least in Python 2.) (至少在Python 2中。)

So this is valid: 所以这是有效的:

def myfunc(foo, bar, *args):
    pass

but this is not: 但这不是:

def myfunc(foo, *args, bar):
    pass

-- -

As @Padraic Cunningham pointed out in the comments, also note that you have a second syntax error: the trailing comma after colors = None . 正如@Padraic Cunningham在评论中指出的那样,还请注意您还有第二个语法错误: colors = None后的尾随逗号。 And your call to super() will fail at run time. 而且您对super()调用将在运行时失败。 You probably want super(palette, self).__init__(*args) . 您可能需要super(palette, self).__init__(*args)

An argument signature like func(self, *args, name=None, colors=None) specifies name and colors as keyword-only arguments . func(self, *args, name=None, colors=None)类的参数签名将namecolors指定为仅关键字的参数 This is only possible in Python 3. If you want your code to work with Python 2, you need to move the *args to the end of the argument list (and accept that arguments passed positionally will fill in name and colors ). 这仅在Python 3中是可能的。如果希望代码与Python 2一起使用,则需要将*args移动到参数列表的末尾(并接受位置传递的参数将填充namecolors )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM