代码之家  ›  专栏  ›  技术社区  ›  multigoodverse

为什么子类化str或int与子类化list或dict的行为不同?

  •  1
  • multigoodverse  · 技术社区  · 7 年前

    从字符串继承传递给的值时 argument

    class StringChild(str):
    
        def __init__(self, argument):
            self.argument = argument
    
    print(Child("text"))
    

    输出:

    text
    

    class IntChild(int):
    
        def __init__(self, argument):
            self.argument = argument
    
    print(IntChild(10))
    

    输出:

    10
    

    但是,当我从列表或dict继承时,我分别得到一个空列表或dict:

    class ListChild(list):
    
        def __init__(self, argument):
            self.argument = argument
    
    print(ListChild([1,2,3]))
    

    []
    

    1 回复  |  直到 7 年前
        1
  •  4
  •   DeepSpace    7 年前

    初始化 self.argument = argument 真正地 argument .

    如果您使用的是一个相当不错的IDE,您应该会看到一条警告 Call to __init__ of super class is missing

    如果您这样做,您将得到您的列表:

    class ListChild(list):
        def __init__(self, argument):
            super().__init__(argument)
            # self.argument = argument
    
    print(ListChild([1, 2, 3]))
    # [1, 2, 3]
    

    self.argument .

    现在,您将在子类化时看到相同的警告 int 也两者的区别 int list 是吗 int 是原始的,工作原理有点不同。你甚至不需要通过考试 super().__init__ . 但是,您需要将其传递给 IntChild.__init__ :

    class IntChild(int):
        def __init__(self, argument):
            super().__init__()
    
    print(IntChild(3))
    # 3
    

    this question int 作品

    鼓励用户使用子类 collections.UserList collections.UserString 列表 str UserInt

    推荐文章