`super()`关键字在列表理解中无法正常工作

时间:2019-12-29 16:01:13

标签: python python-3.x

我正在使用Python 3.7,并且在以下代码中出现错误。看来super()关键字无法正确使用列表推导功能。我想知道原因。

class A(object):
    def hello(self):
        return 1

class B(A):
    def __init__(self):
        why_error = [
            super().hello() for i in range(2) for j in range(2)
        ]
        print(why_error)

class C(A):
    def __init__(self):
        why_no_error = [
            super().hello(),
            super().hello(),
            super().hello(),
            super().hello()
        ]
        print(why_no_error)

c = C()
b = B()

执行结果如下。

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    b = B()
  File "test.py", line 8, in __init__
    super().hello() for i in range(2) for j in range(2)
  File "test.py", line 8, in <listcomp>
    super().hello() for i in range(2) for j in range(2)
TypeError: super(type, obj): obj must be an instance or subtype of type

1 个答案:

答案 0 :(得分:3)

理解是在单独的范围内运行的-这也是为什么ij不泄漏的原因-方法中的嵌套。对于这样的嵌套作用域,无法为零参数超级自动插入__class__self

使用super的两个参数形式:

class B(A):
    def __init__(self):
        why_error = [
            super(B, self).hello() for i in range(2) for j in range(2)
        ]
        print(why_error)

对于类C,将使用列表 literal ,而不是列表 comprehension 。文字不使用单独的作用域。

  

Displays for lists, sets and dictionaries

     

为了构造列表,集合或字典,Python提供了称为“显示”的特殊语法,每种语法有两种形式:

     
      
  • 明确列出容器的内容,或
  •   
  • 它们是通过一组称为理解的循环和过滤指令来计算的。
  •   
     

[...]

     

但是,除了最左边的for子句中的可迭代表达式之外,理解是在单独的隐式嵌套范围内执行的。这样可以确保在目标列表中分配的名称不会“泄漏”到封闭范围内。