【问题标题】:I want to know how to delete a value inside a class我想知道如何删除类中的值
【发布时间】:2018-11-12 13:34:42
【问题描述】:

我在使用 delContact 方法时遇到了困难,因为我想删除类似于 delVar 的对象,但我不知道如何尝试 all = None 或 del all。但是当我在 delContact() 之后调用 show 方法/函数时,我想删除的值仍然显示

class Phonebook:

    def __init__(self,name,type,email,phone):

        self.name = name
        self.type = type
        self.email = email
        self.phone = phone

        print('Adding {} as a Contact with an email of {} and a phone number of {}'.format(self.name,self.email,self.phone))

    def tell(self):

        print('Name: {} | Type: {} | Email: {} | Phone: {}'.format(self.name,self.type,self.email,self.phone))

    def retName(self):

        return  self.name

All = []

def addContact():
    name = input('Enter your the name please: ')
    type = input('Enter the type of the Contact Please: ')
    email = input('Enter the the email of the Contact Please: ')
    phone = input('Enter the Phone number of the Contact Please: ')

    merge = Phonebook(name,type,email,phone)

    All.append(merge)

def show():

    for all in All:
        all.tell()

def delContact():

    show()

    delVar = input('Enter the name you want to delete: ')

    for all in All:

        if all.retName() == delVar:
            print(all.retName())
            all = ''
        else:
            continue



addContact()
addContact()
show()
delContact()
show()

【问题讨论】:

  • 您忘记将 self 添加为方法的默认参数。还要创建一个对象,然后调用方法。如果您不打算将您的方法用于实例,那么您将无缘无故地拥有一个构造函数
  • @PrakashPalnati 你到底在说什么?

标签: python python-3.x


【解决方案1】:

这里:

for all in All:
    if all.retName() == delVar:
        print(all.retName())
        all = ''

您没有删除任何内容,您只是将本地名称 all 重新绑定到空字符串。要从列表中删除该项目,您必须使用All.remove(item)

for all in All:
    if all.retName() == delVar:
        All.remove(all)
        break

请注意,如果您有多个同名项目,这只会删除第一个...

另请注意,修改您正在迭代的列表可能会导致意外结果。在这种情况下它是安全的,因为我们会立即跳出循环,但它通常是可以避免的。

另一种更安全并且会删除所有匹配项的解决方案是过滤掉列表并用结果替换原始列表:

All[:] = [item for item in All if item.name != delVar]

哦,是的,你的 retName 方法完全没用,name 是你类的公共属性。

【讨论】:

  • 先生,非常感谢。如果我想在我的联系人列表中编辑一些东西呢?
猜你喜欢
  • 1970-01-01
  • 2022-08-24
  • 2019-01-04
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多