如何从python类中删除实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从python类中删除实例相关的知识,希望对你有一定的参考价值。
我之前已经问过这个问题但是被告知我包含了太多不必要的代码,所以我现在要用更少的代码询问,希望我所包含的更多是正常的。
我想让一名成员离开团队,如果他们愿意的话。通过这样做,系统将从系统中删除所有细节。我的代码收到错误。有人可以告诉我我做错了什么以及如何实现这一目标?
我想根据用户输入和成员的需要,添加成员并删除成员以便一直更新。我希望这是有道理的!
以下是我的代码:
all_users = []
class Team(object):
members = [] # create an empty list to store data
user_id = 1
def __init__(self, first, last, address):
self.user_id = User.user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '@python.com'
Team.user_id += 1
@staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
first_name = input("What's your first name?
")
second_name = input("What's your surname?
")
address = input("Where do you live?
")
unique_id = input("Finally, what is your User ID?
")
unique_id = int(unique_id)
for i in enumerate(all_users):
if Team.user_id == unique_id:
all_users.remove[i]
def main():
user_1 = Team('chris', 'eel', 'london')
user_2 = Team('carl', 'jack', 'chelsea')
continue_program = True
while continue_program:
print("1. View all members")
print("2. Want to join the team?")
print("3. Need to leave the team?")
print("4. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member()
elif choice == 3:
Team.remove_member()
elif choice == 4:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
main()
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
if __name__ == "__main__":
main()
答案
让我们关注删除代码:
for i in enumerate(all_users):
if Team.user_id == unique_id:
all_users.remove[i]
enumerate
返回两个值:索引和索引处的对象。在你的情况下,i
是这两个值的tuple
。 .remove
是一个功能,而不是一个集合所以.remove[i]
将失败。即便如此,它还是错误的工具:它会扫描列表中的i
并将其删除。你只想删除。最后,一旦更改了列表,就需要停止枚举。
所以,要清理它:
for i, user in enumerate(all_users):
if user.user_id == unique_id:
del all_users[i]
break
以上是关于如何从python类中删除实例的主要内容,如果未能解决你的问题,请参考以下文章