【问题标题】:Overriding constructors for list in python在python中覆盖列表的构造函数
【发布时间】:2021-03-18 20:49:14
【问题描述】:

假设我想在 python 中实现一些具有额外结构的 list 类,比如一个新的构造函数。我写道:

import random

class Lis(list):
    def __init__(self, n):
        self = []
        for i in range(n):
            self.append(random.randint(0, 30))

现在Lis(3) 给了我一个空列表。我不知道我哪里做错了。

【问题讨论】:

    标签: python constructor


    【解决方案1】:

    您正在使用self = [] 覆盖对象

    试试下面的

    import random
    
    class Lis(list):
        def __init__(self, n):
            for i in range(n):
                self.append(random.randint(0, 30))
    

    【讨论】:

    • 感谢您的快速回答,您太快了,我无法接受(暂时不接受您的回答:)
    • super().__init__()
    • 也许你认为是最普遍的。 @James 的答案看起来有点棘手。也许我错了。
    【解决方案2】:

    如果你想从对象调用中返回一个列表

    class MyClass(object):
        def __init__(self):
            print "never called in this case"
        def __new__(cls):
            return [1,2,3]
    
    obj = MyClass()
    print(obj)
    

    How to return a value from __init__ in Python?

    或者如果你想要一个修改过的对象试试:

    class MyClass:
        def __getitem__(self, key):
            not_self = []
            for i in range(n):
                not_self.append(random.randint(0, 30))
            return not_self
    myobj = MyClass()
    
    myobj[3] #Output: 6
    

    How to override the [] operator in Python?

    我不确定像你那样使用 self 是否健康。

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2014-06-09
      • 2018-03-15
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多