【问题标题】:Problem adding and deleting objects from python class从 python 类中添加和删除对象的问题
【发布时间】:2021-03-20 11:17:54
【问题描述】:

请有人帮我修复代码,我想创建一个学校班级并创建一个对象。之后,我想使用join函数添加学生(如果有学生则不添加并显示消息,如果不存在则添加学生),与离开功能相同(它将删除仅当存在时才从列表中)。最后,show_all 函数将显示列表中的所有值。我认为代码的结构是错误的,所以请有人帮助我

class School:
    
    def __init__(self):
        print("A class has opened!")

    def join(self, student):
        self.student = student
        if self.student not in my_school:
            print(self.student +" is a new member of the school!")
        
        else:
            print("We already have "+ self.student +".")
        
    def leave(self):
        if self.student in my_school:
            del self.student
        
        else:
            print("No such student")
            
        
    def show_all(self):
        print(my_school)

# create new object in class
my_school = School() 

# add the student if not exists only
my_school.join('Sarah') 
# delete if exists
my_school.leave("Noor")
# show all the list
my_school.show_all()

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。

标签: python oop


【解决方案1】:

您的代码有几个错误:

  1. 当您调用 join(一个错误的方法名称,因为它已经存在)时,您会将学生重新分配给单个变量。
  2. 请假你引用的实例女巫是不可能的,因为它不存在。

这里有一些代码:

class School:
    
    def __init__(self):
        print("An instance of School was created!")
        self.students = []

    def join(self, student):
        if student not in self.students:
            self.students.append(student)
            print(student + " is a new member of the school!")
        else:
            print("We already have "+ student +".")
        
    def leave(self, student):
        if student in self.students:
            self.students.remove(student)
        else:
            print("No such student")
            
    def show_all(self):
        print(self.students)

# create new object in class
my_school = School() 

# add the student if not in students
my_school.join("Sarah")

# delete the student if in the students list
my_school.leave("Noor")

# print the students
my_school.show_all()

这绝不是好的代码,但接近你想要实现的目标。

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2014-09-28
    相关资源
    最近更新 更多