【问题标题】:Unable to run a simple python program无法运行简单的python程序
【发布时间】:2018-04-17 04:22:33
【问题描述】:

我开始学习python。这是一个简单的程序:

class StudentRepo:
    def __init__(self):
        self.student_list = []

    def add(self, student):
        self.student_list.append(student)

    def get_list(self):
        self.student_list




class Student:
    def __init__(self, name, age):
        self.age = age
        self.name = name




from models.student.Student import Student
from services.student.StudentRepo import StudentRepo

s1 = Student("A", 10)
s2 = Student("B", 11)

# What is the issue here ?
StudentRepo.add(s1)
StudentRepo.add(s2)

studentList = StudentRepo.get_list()
for student in studentList:
    print(student.name)

s1 = Student("A", 10) 有什么问题?

【问题讨论】:

  • 如果您发布收到的异常会很有帮助,因为您描述问题出在s1 = Student("A", 10),但看起来您遇到的问题是因为您尚未创建 @ 的实例987654326@你直接在课堂上打电话。
  • @JohnnyMopp 我不确定 OP 是否正在寻找 staticmethod,因为他们正在操作在 __init__() 中创建的实例变量。
  • 有关如何写出好问题的更多建议,请参阅:stackoverflow.com/help/how-to-ask

标签: python


【解决方案1】:

您的代码中有两个错误。首先,这个:

def get_list(self):
    self.student_list

应该是:

def get_list(self):
    return self.student_list

其次,您正在使用 StudentRepo 类,您应该在其中使用 StudentRepo 的实例:

s1 = Student("A", 10)
s2 = Student("B", 11)

my_roster = StudentRepo()

my_roster.add(s1)
my_roster.add(s2)

studentList = my_roster.get_list()
for student in studentList:
    print(student.name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2021-02-14
    相关资源
    最近更新 更多