簡體   English   中英

如何覆蓋python列表中的init方法?

[英]How do I override the init method in python list?

我需要繼承列表類並重寫init ()方法以獲取參數a,b。 a應該是我要初始化的列表的長度,而b應該是列表中的Items之間的步驟。 我只是不知道從哪里覆蓋init方法。

def myclass(list):
    def __init__(a,b,*args, **kwargs):
         pass

我不知道該怎么辦。

我已經知道我可以這樣做:

class MyClass(list):
    def __init__(a,b):
        data =[x for x in range(0,a*b,b)]
        list.__init__(self,data)

但是我不熟悉python如何實現列表類,例如如何使用剛剛通過的列表理解。

您應該使用super來調用list方法,在這種情況下,它將看起來像這樣:

class myclass(list):
    def __init__(self, a, b, *args, **kwargs):
        super(myclass, self).__init__() # this will call the list init
        # do whatever you need with a and b

l = myclass(10, 0)
l.append(10) # this will calls list append, since it wasn't overriden.
print l
#!/usr/bin/python


class myclass:

    # use the init to pass the arguments to self/the class
    def __init__(self, list, num):
        self.list = list
        self.num = num


    # use this to use the variables
    def use_the_stuff(self):
        #prints the item in the given place
        # i.e in a list of ["A","B","C"] 
        # if self.num is 0, then A will be printed.
        print self.list[self.num]


list_abc = ["A", "B", "C"]
myclass(list_abc, 2).use_the_stuff()

基本上使用帶有init的類來接收列表並對其進行處理。

感謝大家的回應。 意識到我可以通過這種方式實現我想要的:

class myclass(list):
    def __init__(self,a,b):
        data =[x for x in range(0,a*b,b)]
        self.length = len(data)
        super(myclass, self).__init__()
        self.extend(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM