如何将数字添加到列表中,然后通过调用另一个文件中的函数返回列表中整数的总数?

问题描述 投票:0回答:1

我应该实现两个操作,用于在容器(也称为列表)中添加和删除数字。

  1. add(self, value: int) -> int
    – 此函数应将指定的整数
    value
    添加到容器中,并返回添加后列表中整数的数量。
  2. delete(self, value: int) -> bool
    – 应尝试从容器中删除整数
    value
    。如果容器/列表中存在
    value
    ,则将其删除并返回
    True
    ,否则返回
    False

我不知道如何从其他 Python 文件/类中调用

add()
delete()
函数。

有人可以帮我吗:

  1. 从其他 Python 文件和类调用
    add()
    函数的逻辑。
  2. 了解调用
    add()
    函数时 return 语句如何工作。

运行我编写逻辑的文件时收到以下错误消息:

IntegerList.add(containerList)
TypeError: add() missing 1 required positional argument: 'value'

我假设上面的内容是说我没有传递

add()
函数所期望的两个参数/参数,对吧?但如果是这样的话,我会传入什么?

应该从其中调用添加和删除函数的文件(不可编辑):

from abc import ABC

class IntegerList(ABC):
    def add(self, value: int) -> int:
        #Should add the specified integer 'value' to the container and return the 
        #number of integers in the container after the addition.
        return 0
    
    def delete(self, value: int) -> bool:
        #Should attempt to remove the specified integer 'value' from the container.
        #If the 'value' is present in the container, remove it and return 'True', otherwise, return 'False.'
        return False

我试图在其中写入逻辑并调用添加/删除函数的可编辑文件:

from int_list import IntegerList**

class IntegerContainerImpl(IntegerList):
    def __init__(self) -> None:
        pass
    
    # The crud I wrote below....
    containerList = []
    integerNumber = int(input("Add number of container: "))
    containerList.append(integerNumber)
    IntegerList.add(containerList)

我不知道在

__init__
函数中要包含什么。我知道这些是默认构造函数。

我期待着一些事情,比如:

return 1; container: [1] #added 1 to the list
return 2; container: [1,4] #added 4 to the list
return 3; container: [1,4,3] #added 3 to the list
return True: container: [1,3] #removed 4 from the list
return False: container: [1,3] #attempted to remove the number 2 from the list, which doesn't exist, hence the return is false
python list function class
1个回答
0
投票

只需从

IntegerList

制作一个对象
from int_list import IntegerList

class IntegerContainerImpl(IntegerList):
    def __init__(self) -> None:
        pass
    


    containerList = []
    integerNumber = int(input("Add number of container: "))
    containerList.append(integerNumber)
    IntegerListObject = IntegerList()
    IntegerList_.add(containerList)

附加到对象而不是类

IntegerListObject = IntegerList()
IntegerList_.add(containerList)
© www.soinside.com 2019 - 2024. All rights reserved.