无法使用以下类执行以下代码:
预期结果=[1,2,3,4,90,25]给定结果= <<strong>main
我怎样才能阻止这种情况的发生?没有内置的extend()
感谢您的帮助
class ArrayList:
def __init__(self):
self.inArray = []
self.count = 0
def appendAll(self, e):
newArray = [0 for i in range(len(self.inArray)+1)]
for i in range(len(self.inArray)):
newArray[i] = self.inArray[i]
newArray[len(self.inArray)] = e
self.inArray = newArray
ls = [1, 2, 3, 4]
ls = ArrayList()
ls.appendAll([90, 25])
print(ls)
这是因为Python默认返回对用户定义的类对象的引用,而不是它的数据成员。
class ArrayList:
def __init__(self, inArray: list = []):
self.inArray = inArray
self.count : int = 0
def appendAll(self, newArray: list):
self.inArray.extend(newArray) # extend() can add multiple values at a time
def __str__(self): # __str__ is a magic/dunder method (Special function reserved in Python which gets activated when you try to print an object of it's class)
return str(self.inArray)
if __name__=='__main__':
ls = ArrayList([1, 2, 3, 4]) # Initialize ArrayList object with default value
ls.appendAll([90, 25]) # Add more values
print(ls)
我已经纠正了你的代码,并为你增加了概念,称为:
1类型提示
2。主要'"功能