我正在創建一個mylist從listpython繼承的自定義類。
但我無法附加值
class mylist(list):
def __init__(self,max_length):
super().__init__()
self.max_length = max_length
def append(self, *args, **kwargs):
""" Append object to the end of the list. """
if len(self) > self.max_length:
raise Exception
a = mylist(5)
a.append(5)
print(a)
# output
#[]
uj5u.com熱心網友回復:
您定義了自己的,append()因此您替換了原始內容append(),并且不會將元素添加到串列中。
你可以super()用來運行原始的append()
def append(self, *args, **kwargs):
""" Append object to the end of the list. """
if len(self) > self.max_length:
raise Exception
if args:
super().append(args[0])
我認為你應該使用>=而不是>因為你在添加專案之前檢查它。>如果您在添加專案后檢查它,您可以使用
順便提一句:
因為你使用*args所以你可以使用for-loop 來追加可能值a.append(5, 6, 7)。原來的append()做不到。
for item in args:
super().append(item)
它可能需要檢查是否len(self) len(args) > self.max_length或可能需要檢查len(self)內for回圈
您還可以檢查是否args有任何值并在a.append()沒有任何值的情況下運行時引發錯誤。
class MyList(list): # PEP8: `CamelCaseNames` for classes
def __init__(self, max_length):
super().__init__()
self.max_length = max_length
def append(self, *args, **kwargs):
""" Append object to the end of the list. """
#if len(self) >= self.max_length:
# raise Exception
#if args:
# super().append(args[0])
if not args: # use `TypeError` like in `list.append()`
raise TypeError("descriptor 'append' of 'list' object needs an argument")
for item in args:
if len(self) >= self.max_length:
raise Exception
super().append(item)
def insert(self, pos, value):
if len(self) >= self.max_length:
raise Exception
super().insert(pos, value)
# --- main ---
#list.append() # raise `TypeError`
a = MyList(5)
try:
a.append() # raise `TypeError` like in `list.append()`
except Exception as ex:
print('ex:', ex)
a.append(5)
print(a) # [5]
a.append(6, 7, 8, 9)
print(a) # [5, 6, 7, 8, 9]
a.append(10) # raise ERROR
a.insert(0, 999) # raise ERROR
PEP 8 -- Python 代碼風格指南
uj5u.com熱心網友回復:
你是這個意思?
class mylist(list):
def __init__(self,lists:list,max_length:int):
super().__init__()
self.lists = lists
self.max_length = max_length
def get_list(self):
return self.lists
def append(self, *args, **kwargs):
if len(self.lists) > self.max_length:
raise Exception
else:
self.lists.append(*args)
a = mylist([5,4,3,2])
a.append(54)
print(a.lists)
#OR
print(a.get_list())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314615.html
上一篇:如何將物件陣列傳遞給函式?
下一篇:從物件陣列訪問屬性值c#
