[英]how can I define python class with list attribute and the class constructor that accept variable arguments?
如何將 python 屬性定義為 class? 我想定義一個 Python class 來實例化列表類型的對象。 我可以使用__init__
和 class 方法來做到這一點,但我正在尋找一種避免使用方法的方法。 第二個問題是我想知道是否可以使用接受變量 arguments 的構造函數定義 class (例如,使用此 class 實例化具有不同索引數的對象([4,5,6] ,4,7])。我在下面復制了我的代碼。感謝您的幫助:)
class SuperList(list):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def My_list(self):
return [self.a, self.b, self.c]
obj1 = SuperList(1, 2, 3)
List1 = obj1.My_list()
List1.append(8)
print(List1)
我不確定您要使用“類生成列表”實現什么目標,但可以在下面找到一個示例,該示例可能會讓您更好地理解。
當您從list
繼承時,只需執行以下操作,您將擁有一個自定義列表實現:
class SuperList(list):
def __init__(self, *args):
super().__init__(args)
list1 = SuperList(1, 2, 3)
list1.append(8)
print(list1)
list2 = SuperList(1, 2, 3, 7, 8, 9)
list2.append(999)
print(list2)
class SuperList(list):
def __init__(self,*a):
self.myList = list(a)
def My_list(self):
return self.myList
這適用於多個參數
obj1 = SuperList(1, 2, 54, 3)
print(obj1.My_list())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.