[英]How to delete an instance from a python class
我之前曾問過這個問題,但被告知我包含了太多不必要的代碼,所以現在我要用更少的代碼問,希望我包含的內容更多。
我試圖允許成員離開團隊,如果他們願意的話。 這樣,系統將從系統中刪除其所有詳細信息。 我的代碼收到錯誤。 有人可以告訴我我在做什么錯,以及如何做到這一點?
我希望我的添加成員和刪除成員能夠始終根據用戶輸入和成員的需求進行更新。 我希望這是有道理的!
下面是我的代碼:
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?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
unique_id = input("Finally, what is your User ID?\n")
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.